Re: Problems with inheritance!
Tor Iver Wilhelmsen wrote:
"nullstring" <leerstring@gmail.com> writes:
sub.additionalFuntion(); //this method isn't available!
//why? I have a concrete
refenence from type object_1,
//so why I can't call all
object_1-functions???
Because there is a distinction between type-of-reference (which the
compiler uses to decide what members are visible) and type-of-objkect
(which the runtime uses to select the actual method invoked).
To call additionalFunction() you need to cast to object_1 first.
Besides that, it seems you need to rethink your inheritance hierarchy.
You haven't said much about your goal, but
If I have 5 subclasses (object_1, object_2, .... , object_5) I can hold
5 object-references.
But I don't want to do this....
Is there any possibility, the realize it that way that I wanted it?
(with one reference)
while hard for me to understand what you mean, seems to indicate that you
correlate types with object references, which is not a very precise view.
Inheritance models an "is-a" relationship, as in "Rectangle is-a Shape". Can
you say that your subclass represents a thing that "is a" member of the supertype?
Interfaces are raw types that define for all clients how a service class must
operate. They represent a behavioral contract. Can you say that all your
subclasses behave according to the interface contract?
Let us say that you have a class Foo with methodA() and methodB(). You want
some subclasses to implement a methodC(), belonging to interface Bar.
public class Foo
{
public void methodA() { ... }
public void methodB() ( ... }
}
public interface Bar
{
void methodC();
}
public class FooSub extends Foo implements Bar
{
public void methodC() { ... }
}
Now class FooSub "is a" Foo, and also FooSub "is a" Bar. FooSub has all three
methods.
public class TestFoos
{
public static void main( String [] args )
{
FooSub sub = new FooSub();
sub.methodA();
sub.methodC();
Foo foo = sub;
foo.methodA();
// foo.methodC(); // <== ILLEGAL! wrong compile-time type
((FooSub) foo).methodC(); // LEGAL if foo is rt type FooSub
Bar bar = sub;
bar.methodC();
// bar.methodA(); // <== ILLEGAL! wrong compile-time type
((FooSub) bar).methodA(); // LEGAL if bar is rt type FooSub
}
}
Note that in general downcasts like this are subject to ClassCastException
hurling if their run-time (rt) types don't match.
- Lew