aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes jq+ Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "jq+ Question" Watch "jq+ Question" New topic
Author

jq+ Question

brent spearios
Ranch Hand

Joined: Apr 10, 2002
Posts: 48
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

Joined: Aug 26, 2001
Posts: 7610
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.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
brent spearios
Ranch Hand

Joined: Apr 10, 2002
Posts: 48
Thanks. Really helped to clear things up.
Mag Hoehme
Ranch Hand

Joined: Apr 07, 2002
Posts: 194
The matter is also explained at
JLS 15.11.1


Mag
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: jq+ Question