File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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

I agree. Here's the link:
subject: jq+ Question
Similar Threads
start and run method
Why This????
inheritance for Object class
[Comparable] problem with ording classes
Java Rule Round-Up