Why we need to create method in subclass to acess methods in Superclass in Java programming language.?

I am currently learning OOP in java. One thing I came across is that, for example, i have a method speed in Vehicle SUPERCLASS, and I want to access that method in SUBCLASS Car, i will have to create method like;

public void changespeed()
{
  super.speed();
}

in order to access speed method. My question is, why we need to enclose speed method like that in order to access it? why cant we just simply use this approach;

super.speed();

to call that speed method in subclass. ?

1 answer

  • answered 2018-08-09 00:18 Sweeper

    You can just do this:

    speed();
    

    Since non-private superclass methods are all inherited by the subclass, speed also exists in the subclass. You can access it by this.speed(), or just speed().

    Obviously, you have to put this method call in an appropriate place. You can't just randomly put it in a class like this:

    class Car extends Vehicle {
        speed(); // can't do this!
    }
    

    You have to put the method call in, among other things, another method or a constructor. This way the compiler knows when the method will be called.

    Why do method calls have to be in other methods or constructors?

    Well, ask yourself when the method call in the above snippet will be called. Remember that speed is an instance method, so an instance of Car is needed to call it. Where's that instance? This whole notion of putting methods directly in a class makes little sense.

    So what if I want a method to be called when the class is loaded?

    You can use a static block for that purpose:

    static {
        // do stuff here
    }
    

    Note that you still can't call speed directly in a static block because you need an instance of Car or Vehicle.