This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "jq+ Question" Watch "jq+ Question" New topic

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
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Welcome to Javaranch
First off, let's see what
test y=new test2();
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.

[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

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: jq+ Question
Similar Threads
Java Rule Round-Up
inheritance for Object class
start and run method
Why This????
[Comparable] problem with ording classes