• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

jq+ Question

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can any one help me with this:
class test{
int i=8;
//public test(){
public void t(){
System.out.println ("test");
}
//}

}
class test2 extends test{
//public test2(){
int i=9;
public void t(){
System.out.println ("test2");
}
//}
public static void main(String args[]){
test y=new test2();
System.out.println (y.i);
y.t ();
}
}

Why does it print out 8 test2 and not 9 test2
thanx
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to Javaranch
First off, let's see what
test y=new test2();
means:
you are declaring a variable 'y' of type 'test' referencing an object of type 'test2'. This is possible because class test is a superclass of class test2. Then, the resolution of the member instance 'i' is based on the compile-time type (the type of the reference variable), that is, 'test' and not 'test2', hence the value 8 being printed out.
Concerning the method lookup, you have to know that instance methods are looked up dynamically at runtime (static methods are not) and the resolution process bases itself on the runtime type (the type of the referenced object) of 'y', that is, 'test2' and not 'test'. From there, you can deduce the correct answer.
 
brent spearios
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks. Really helped to clear things up.
 
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The matter is also explained at
JLS 15.11.1
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic