• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Overridding

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
So you made a portal in time and started grabbing people. This tiny ad thinks that's rude:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic