Why superclass object cannot be implicitly converted to subclass object in Java?

前端 未结 4 1287
日久生厌
日久生厌 2020-12-30 17:05

I have the following code:

class A {
}

class B extends A {
    public void fB(){};
}

According to Java rule:

Case 1:



        
4条回答
  •  旧巷少年郎
    2020-12-30 17:44

    Suppose case 2 is also working, then your compiler sees "b" as a object of class "B". Now you can say "b.fb()". But actually "b" is an object of "A"(Remember you assigned an object of class "A" to "b"). there is no function fb() in class "A". your application crashes!!

提交回复
热议问题