Use of 'super' keyword when accessing non-overridden superclass methods

Posted by jonny on Stack Overflow See other posts from Stack Overflow or by jonny
Published on 2012-10-09T15:23:07Z Indexed on 2012/10/09 15:37 UTC
Read the original article Hit count: 241

Filed under:
|

I'm trying to get the hang of inheritance in Java and have learnt that when overriding methods (and hiding fields) in sub classes, they can still be accessed from the super class by using the 'super' keyword.

What I want to know is, should the 'super' keyword be used for non-overridden methods?

Is there any difference (for non-overridden methods / non-hidden fields)?

I've put together an example below.

public class Vehicle {
    public int tyreCost;

    public Vehicle(int tyreCost) {
         this.tyreCost = tyreCost;
    }

    public int getTyreCost() {
        return tyreCost;
    }        
}

and

public class Car extends Vehicle {
    public int wheelCount;

    public Vehicle(int tyreCost, int wheelCount) {
        super(tyreCost);
        this.wheelCount = wheelCount;
    }   

    public int getTotalTyreReplacementCost() {
        return getTyreCost() * wheelCount;
    }   
}

Specifically, given that getTyreCost() hasn't been overridden, should getTotalTyreReplacementCost() use getTyreCost(), or super.getTyreCost() ?

I'm wondering whether super should be used in all instances where fields or methods of the superclass are accessed (to show in the code that you are accessing the superclass), or only in the overridden/hidden ones (so they stand out).

© Stack Overflow or respective owner

Related posts about java

Related posts about coding-style