Why should I reference the base class when I can access all the methods just as well by referencing the subclass?

后端 未结 6 1711
后悔当初
后悔当初 2021-01-20 14:32

I am learning java concepts. I got a doubt in java inheritance concept. In inheritance we can assign subclass instance to a base class reference and with that we can access

6条回答
  •  迷失自我
    2021-01-20 15:13

    Let us say Vehicle is the base class and Car and Plane are subclasses. Let us say Vehicle has has a method move().

    Car overrides this by going on road. Plane overrides this by flying.

    Why move() should be part of Vehicle base class?

    Because any Vehicle can move(). But we can't implement move() in Vehicle because all vehicles doesn't move the same way i.e. there is no common behavior. We still want this in the base class so that we can have polymorphic behavior i.e. we can write code like below. As you can see there is only one method called runVehicle(...) that can work on any Vehicle class.

    void runVehicle(Vehicle v)
    {
      v.move();
    }
    
    Car c=new Car();
    runVehicle(c);
    
    Plane p=new Plane();
    runPlane(p);
    

提交回复
热议问题