• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

jq+ Question

 
brent spearios
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • 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
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks. Really helped to clear things up.
 
Mag Hoehme
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The matter is also explained at
JLS 15.11.1
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic