I do not understand the explaination by the book. Could someone please elaborate on it.
"If you use a reference variable of type Object, you can access only those members defined in class Object."
Is this saying that the code fails to compile as the Object class does not have a public String variable named 'horse'?
Thanks.
OCPJP 6
John Jai
Rancher
Joined: May 31, 2011
Posts: 1372
posted
2
The concept is that when you use your base class reference to refer child class instance polymorphically, you can call only those methods defined in the base class using the base class reference.
Though the base class reference is holding a child class instance it's not possible and allowed to call child class specific methods.
See below program, a football player is a person and so is a tennis player. you cannot ask a football player to play tennis and vice versa.
Hiral Jhaveri
Greenhorn
Joined: Nov 23, 2011
Posts: 5
posted
1
Yes. You understood it right. Since the reference is of classtype Object.
So, using this reference we can only access the fields (or methods) that are defined in class Object.
Though the actual object is of classtype Horse, the compiler doesn't know this, so it gives error!
In order to access name, our reference must be first type-casted to Horse, and then name can be accessed.
Again, here type-casting works (without compilation error or Exception at runtime) because the actual object is of classtype Horse.
Joseph Arnold
Ranch Hand
Joined: Oct 05, 2010
Posts: 42
posted
0
Object obj = new Horse("Zippo");
Here is the reference type is Object and hence you can only access members of object and not horse.
If you want to use a access a method/property of Horse, you should simple use the horse reference type itself.
Look at it this way, the only reason Java allows you have to have a base class refer to a sub class type is to make use of polymorphism. Conceptually, a base class reference is used to access a property that is common to all subclasses and not a property pertaining to a particular sub class(here name belongs only to horse).
Common properties of several classes are identified and are put in a common class called the Base class. That is the idea behind inheritance.