Search code examples
javaobjectinheritance

Simple question about Inheritance in Java


I have a question about inheritance. If I wanna call a method from the parent class in the child class, should I either use super.method() or this.method()? In the programs I'm programming, they both work so I'm using both of them but I don't really think that this is the right way.

For instance, let's say I have a class called "Vehicle" and another which we will call "Airplane". Let's say I have a brand() method in Vehicle. Should I either use this.brand() or super.brand()?


Solution

  • Consider this code snippet,

    class Vehicle {
        public void brand(){
            System.out.println("This is a vehicle");
        }
    }
    
    class Airplane extends Vehicle {
        public void brand() {
            System.out.println("This is an airplane");
        }
    
        public void anotherMethodInAirplane() {
            this.brand();
            super.brand();
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Airplane airplane = new Airplane();
            airplane.anotherMethodInAirplane();
        }
    }
    

    If you were to execute this, you would see that this.brand() prints "This is an airplane" first and then super.brand() prints "This is a vehicle".

    So,

    1. If you call super.someMethod(), it will always call the method in your superclass.
    2. If you call this.someMethod() and someMethod() has been overridden by your subclass (Airplane in this example) then that will be called.
    3. However, if someMethod() is not overridden in your subclass, then the super class implementation of someMethod() will be executed by default