Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overridding

 
Ehab Salah
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello there ,
given the following code

class Base {
protected int size = 100;
public int getSize() {
return size;
}
}
class SubClass extends Base{
protected int size = 10;
public int getSize() {
return size;
}
public static void main (String Args[]) {
Base b = new SubClass();
System.out.println(b.size+" "+b.getSize());
}


}

I excpeted the print out would be 10 10

But the answer in the mock exam was 100 10 , why ? I understand that the true object type is the one determine which method / variable to be used at run time , is not ?
 
Reghu Ram Thanumalayan
Ranch Hand
Posts: 193
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Originally posted by Ehab Salah:

I understand that the true object type is the one determine which method / variable to be used at run time , is not ?

You are correct except that this is applicable only for methods and not for variables.

When instance variables with same name are defined in both the base and sub class, the one defined in the subclass hides the one defined in the base class. Also variables are resolved by the type of the reference rather than the actual object assigined to the reference.

What i mean here is when you say Base b = new SubClass(); the type of the reference is Base, so b.size prints 100 whereas calling the method getSize() on b causes the subclass getSize to be called since the method is overridden in the subclass.

Hope this helps.

[ June 30, 2005: Message edited by: Reghu Ram T ]
[ June 30, 2005: Message edited by: Reghu Ram T ]
 
Nicky Eng
Ranch Hand
Posts: 378
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
agree with reghu ram t.

by the way, above question i faced it b4. i hope i can clear my SCJP on saturday....

all the best to all.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic