开发者

inheritance problem OOP extend

开发者 https://www.devze.com 2023-01-02 05:34 出处:网络
If a Father is a Parent and a Parent is a Person and a Person has a Father I create the following: class Person开发者_JAVA百科{

If a Father is a Parent and a Parent is a Person and a Person has a Father I create the following:

 class Person开发者_JAVA百科{
  Father father;
 }
 class Parent extends Person{}
 class Father extends Parent{}

Instances:

Person p1 = new Person();
Person p2 = new Person();
p1.father = p2; //father is of the type Father

This doesn't work... Now try casting::

Person p1 = new Person();
Person p2 = new Person();
p1.father = (Father)p2;

This doesn't work either.

What does work for this case?


Actually, Father is not a sub class of person. It is just a relation.

 class Person {
    Person father;
 }


The most obvious thing is that a Father IS a Person. A Person does NOT have to be a Father though, when it comes to the concrete instance. This example specifically, would work if you father field was of type Person, or you instantiated p2 as a new Father.


You cannot cast like that. Your person is not a father so casting to one won’t work. You can only cast to something that the object is.

Person p1 = new Person();
Person p2 = new Father();
p1.father = (Father)p2;

Or directly:

Father p2 = new Father();
p1.father = p2;

But being a father isn’t a good differentiation in the class hierarchy. I probably wouldn’t create an own class for it: being a father is just one of many roles that one person fulfils so I would remove that class and declare the father member as a regular Person. Same for Parent.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号