Why can't reference to child Class object refer to the parent Class object?

后端 未结 14 1120
执念已碎
执念已碎 2020-12-17 10:50

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

I just escaped by saying, since OOP depicts the real world. In rea

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 11:36

    If I have a class, say

    class A{
        getA(){
    
        }
    }
    
    class B extend A{
        getB(){
    
        }
    }
    

    Now class B knows two methods getA() and getB(). but class A knows only getA() method.

    So, if we have class B obj = new class A(); we have made a mess , as it is valid for class B to reference methods getA() and getB() but only getA() is valid. That explains the issue.

    This is my understanding of not allowing child class hold reference of parent class.

提交回复
热议问题