aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overridding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overridding" Watch "Overridding" New topic
Author

Overridding

Aru
Ranch Hand

Joined: Jul 20, 2000
Posts: 112
Hi,
Can someone explain the output of the code ?
class Test extends Object {
public static void main(String args[]){
Shape p = new Shape();
Shape q = new SubShape();
System.out.println("p.y = " + p.y + " q.y = "+ q.y);
System.out.println(
"p.getY()= "+ p.getY()+"q.getY()="+q.getY());
}
}
class Shape {
int x = 7, y = 7;
public int getY() {return y;}
}
class SubShape extends Shape {
int x =5, y =5;
public int getY() {return y;}
}
The output is
p.y = 7 q.y = 7
p.getY() = 7 q.getY() = 5
If q.y = 7 why is q.getY() = 5 ?
Thx in Advance
Aruna
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I think it has to do with "late binding": when you use a variable, like q in your example, to refer to an object, then invoke a method of that object, the method that's executed is of the object's class, not q's class. But when you access member variables of the object, the variables that are accessed are of q's class.
In your example "Shape q = new SubShape();" means q is of class Shape but refers to an object of class SubShape. So q.y accesses the y in the Shape class, which is 7, but q.getY() executes the getY method in the SubShape class, which returns 5.
For an explanation of late binding, see RHE chapter 6 P. 177 and Mughal & Rasmussen section 6.2 P. 181.
Hope this helps.
Muraleedharan Paruthooli
Greenhorn

Joined: Jul 27, 2000
Posts: 3
Aruna,

You have defined
Shape p = new Shape();
Shape q = new SubShape();
As far as Data members of an object are concerned, they are resolved at the compile time itself. Here both object refernce
varibles p and q are that of Shape.
As far as methods of an object are concerned, they are polymorphic meaning they will be resolved during run-time based on the type of the instance.
If you defined like this,
Shape p = new Shape();
SubShape q = new SubShape();
The output will be
p.y = 7 q.y = 5
p.getY() = 7 q.getY() = 5

Murali
Aru
Ranch Hand

Joined: Jul 20, 2000
Posts: 112
Thanks everyone.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overridding