Re: Problems with inheritance!
nullstring wrote:
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)
Yeah, that helped, thank you very much!
Nullstring
You can use inheritance through interface in that case. Though you
would need to declare the methods in your interface.
Example:-
interface ObjInterface {
public void meth1();
public void meth2();
public void meth3(); // other methods if there are any without any
concrete implementation
}
public class object_1 implements ObjInterface {
public void meth1() {
// concrete implementation
}
}
public class object_2 implements ObjInterface {
public void meth1() {
// concrete implementation
}
}
public class object_3 implements ObjInterface {
public void meth1() {
// concrete implementation
}
}
So on for rest of the object classes. You can refer to all of them like
mentioned below
public class tester {
public static void main(String [] args) {
ObjInterface o1 = new object1(); // you are creating all the objects
of type ObjInterface
o1.meth1(); // invokes concrete implementation of object_1
o1 = new object2();
o1.meth1(); // invokes concrete implementation of object_2
o1 = new object3();
o1.meth1(); // invokes concrete implementation of object_3
}
I think same result can be obtained by extending an abstract or a
concrete class too. Though Interface is a preferred way to design.
Cheers,
Ck
http://www.gfour.net