Reputation: 543
This is a general OOP question for languages that do not support inheritance from multiple classes (not sure if that matters here, just thought I'd put that detail in), like Java:
OK, you have your base class:
class Base {}
class Derived extends Base
{
SomeMethod(){}
}
Main()
{
Base baseInstance = new Base();
Derived derivedInstance = new Derived();
baseInstance = derivedInstance;
baseInstance.someMethod(); <<<<<< this does not work. why?
}
Why, when you set the baseInstance to the derivedInstance, is it unable to call the method that is defined in the Derived class?
Since you're setting the baseInstance to be the derivedInstance, should you not have access to this method?
Upvotes: 0
Views: 130
Reputation: 7804
In java instances are created at runtime, so the actual class instance gets resolved at run-time and not during compilation.
Thus, Compiler always looks at the reference type to determine which methods or members can be referred by the referencing variable.
In your case, baseInstance = derivedInstance;
even though the actual class being referred is a subclass of Base
, compiler will simply assume it to be of the type Base
. Obviously, Base
class does not have someMethod();
hence it does not allow you to call it.
As a work around, you can try this:
if(base instanceof Derived) {
// Downcast it before calling
((Derived)baseInstance).someMethod();
}
Upvotes: 1
Reputation: 1253
This line
baseInstance = derivedInstance;
doesn't set baseInstance
to type Derived
. It's still type Base
.
You can only call someMethod()
on an object of type Base
if someMethod
is a method defined in Base
. The compiler does not know about more derived methods.
Upvotes: 1
Reputation: 1062770
A variable that is typed as the base class cannot presume methods about subclasses. For example, for all the compiler knows, baseInstance
could hold a reference to a Base
, or to a SomeOtherClass extends Base
. Now, you could say that in this case the compiler could figure it out, but: that isn't what the compiler does. The rules of the compiler are simple: if you have a variable typed as Base
, you can only use things known on Base
.
If you want to use specialized methods from specific sub-classes, then you'll need to ask the compiler to perform a cast with type-check, i.e.
Derived special = (Derived)baseInstance; // I'm using C# syntax here,
special.someMethod(); // but should be similar or identical
Upvotes: 6