Typical Hierarchical inheritance in Java

放肆的年华 提交于 2020-01-05 17:57:06

问题


Consider this below code snippet

public class SuperClass {
    public void move()
    {
        System.out.println("i am in super class");
    }
}
public class SubClass1 extends SuperClass{
    public void move()
    {
        System.out.println("i am in sub1 class");
    }

}
public class SubClass2  extends SuperClass {

    public void move()
    {
        System.out.println("i am in sub2 class");
    }

}

Now i am creating object like this.

public class program {
    public static void main(String[] args) {    
            SubClass1 obj = new SubClass2(); // Compile error - Type mismatch: cannot convert from SubClass2 to SubClass1
            obj.move();
    }
}

Why i can't do like this ? What stopping me to write this ??


回答1:


Why i can't do like this ?

SubClass2 is not a SubClass1

What stopping me to write this ??

You cannot actually convert types to references in Java. You can only change the type of a reference to one that the object actually is. What you may have intended is

SuperClass obj = new SubClass2(); // SubClass2 is a SuperClass 
obj.move();

or you could have

public class SubClass2  extends SubClass1 {



回答2:


Because SubClass2 extends SuperClass, not SubClass1.

For example, lets say that SubClass1 also contained a member variable x and a function y(). If you could cast from SubClass2 to SubClass1, the variable x and function y() would not exist, and your program would fail. So Java does not allow this.

The two sub classes are only related to the class(es) they extend, not each other.




回答3:


Its because in polymorphism, you cannot refer one sibling by another sibling. For example, in the picture below, you can do:

Bicycle b1 = new MountainBike();
Bicycle b2 = new RoadBike();
Bicycle b3 = new TandemBike();

because all these have common superclass. But MountainBike, RoadBike and TandemBike cannot refer to each other since they are sibbling.




回答4:


Lets take an example from OOP. the condition is SuperClass parent class of both the child classes SubClass1 & SubClass2.

Now in code you are trying to hold an object of SubClass2 in reference of SubClass1. Now when you try to create a link it will look like below image

Now when you look at the hierarchic Subclasses are have a relation "sibling" not "child-parent" where; since child is derived by parent hence the parent can hold their respective child's object. But this do not imply with Siblings as both can have their own version of behaviors and properties (one can have more other can have less) in this case if java allows or it will be right to say OOP allows sibling to behave like your code the concept of "physical problem implemented pro-grammatically" will go wrong.



来源:https://stackoverflow.com/questions/29337759/typical-hierarchical-inheritance-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!