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 The result of instance variable of inheritance. 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 "The result of instance variable of inheritance." Watch "The result of instance variable of inheritance." New topic
Author

The result of instance variable of inheritance.

Sam Sunamin
Ranch Hand

Joined: Mar 16, 2007
Posts: 113
What's the result of the following code?

public class Question10 {

public A getObject() {
return new A();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Question10 q10 = new SubQuestion10();
System.out.println(q10.getObject()); //line 10
System.out.println(q10.getObject().x); //line 11
}

}

class SubQuestion10 extends Question10{
public B getObject() {
return new B();
}
}

class A{
int x=5;
}

class B extends A{
int x=6;
}

When I run the code, I got the result as:
B@1372a1a
5



My question is why line 11's result is not 6, but 5.
But the result of line 10 is B@1372a1a, not A@1372a1a


Yours Sam<br />SCJP5.0 97%<br />SCBCD5.0 72%
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Sam,

Try this modified code and understand what exactly is happening...



cmbhatt
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: The result of instance variable of inheritance.
 
Similar Threads
Problem in polymorphism
overriding with variables - whizlabs
Query on covariant return --- SCJP 5.0
Polymorphism
Covariant Return Types