Reputation: 69
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()
?
Upvotes: 0
Views: 91
Reputation: 343
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,
Upvotes: 4