为什么不能引用到子Class对象指的是父类对象? [英] Why can't reference to child Class object refer to the parent Class object?

查看:146
本文介绍了为什么不能引用到子Class对象指的是父类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解释OOP给我的朋友。我不能回答这个问题。 (如何可耻我?:()

I was explaining OOP to my friend. I was unable to answer this question. (How shameful of me? :( )

我只是说逃过一劫,因为OOP描绘了真实的世界。在现实世界中,家长可以容纳孩子,但孩子不能容纳父母。同样是在OOP.I的情况下知道它的愚蠢:p

I just escaped by saying, since OOP depicts the real world. In real world, Parent's can accommodate children but children cannot accommodate parents. same is the case in OOP.I know its stupid. :P

class Parent
{
  int prop1;
  int prop2;
}

class Child : Parent // class Child extends Parent  (in case of Java Lang.)
{
  int prop3;
  int prop4;

  public static void Main()
  {
     Child aChild = new Child();
     Parent aParent = new Parent();
     aParent = aChild;// is perfectly valid.
     aChild = aParent;// is not valid. Why??

  }
}

为什么没有这种说法合法吗?

Why isn't this statement valid?

 aChild = aParent;// is not valid. Why??

自aChild的成员是aParent成员的超集,那么为什么不能aChild容纳父。

since aChild's members are superset of aParent's members. Then why can't aChild accommodate a parent.

推荐答案

正因为aChild是aParent的能力的超集。你可以写:

Exactly because aChild is a superset of aParent's abilities. You can write:

class Fox : Animal

由于每个福克斯是动物。但是,另一种是并不总是正确的(不是每个动物就是一个狐狸)。

Because each Fox is an Animal. But the other way is not always true (not every Animal is a Fox).

此外,它似乎是你有你的OOP混合起来。这不是父子关系,因为这里不涉及成分/棵。这是一个祖先/后代继承关系。

Also it seems that you have your OOP mixed up. This is not a Parent-Child relationship, because there's no composition/trees involved. This is a Ancestor/Descendant inheritance relation.

继承是型不包含。因此,它的福克斯是一类动物的,在你的情况下,它不健全的权利 - 孩子是一种家长? 。类的命名是混乱的根源;)

Inheritance is "type of" not "contains". Hence it's Fox is a type of Animal, in your case it doesn't sound right -- "Child is a type of Parent" ? The naming of classes was the source of confusion ;).

class Animal {}
class Fox : Animal {}
class Fish : Animal {}

Animal a = new Fox(); // ok!
Animal b = new Fish(); // ok!
Fox f = b; // obviously no!

这篇关于为什么不能引用到子Class对象指的是父类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆