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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overridding" Watch "Overridding" New topic
Author

Overridding

Ehab Salah
Greenhorn

Joined: Oct 07, 2004
Posts: 1
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

Joined: Oct 21, 2003
Posts: 193
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 ]

Cheers,<br />Reghu Ram T<br /> <br />SCJP 1.4 - 98 %, SCBCD 1.3 - 94 %, SCMAD 1.0 - 92 %
Nicky Eng
Ranch Hand

Joined: Mar 26, 2005
Posts: 378
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.


From NickyEng
Diploma in Computer Studies
SCJP 1.4
SCWCD 1.4
Formula 1 app by Maxis (Playbook)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overridding