I will try to explain it in other way.
Method overriding happens when you redefine a method with the same signature in a sublcass.
For example, we have an Animal class, which has the method move()
Code:
public class Animal {
public Animal() {}
public void move() {
System.out.println("Animal moves!");
}
}
Then we take a subclass of Animal, for example Cat. The Cat class has also the method move() which we are overriding. Plus we will add the miau() method for the Cat class.
Code:
public class Cat extends Animal {
public Cat() {}
public void move() {
System.out.println("Cat moves!");
}
public void miau() {
System.out.println("miauuuu");
}
}
And now lets test it.
Code:
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
Animal c = new Cat();
a.move();
c.move();
}
}
So what is the output here?
Code:
Animal moves!
Cat moves!
We have successfully overriden the move() method.
But what happens if we want to use the miau() method?
Code:
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
Animal c = new Cat();
a.move();
c.move();
c.miau(); // we add this here
}
}
We are getting an error! =>
Code:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method miau() is undefined for the type Animal
The @Override annotation is optional (but a very good thing) and indicates that this is expected to be overriding. If you misspell something or have a wrongly-typed parameter, the compiler will warn you. ==>
Code:
public class Cat extends Animal {
public Cat() {}
@Override
public void move() {
System.out.println("Cat moves!");
}
@Override
public void miau() { // now you get here an error because this method doesn't exist in Animal
System.out.println("miauuuu");
}
}
Output:
Code:
The method miau() of type Cat must override or implement a supertype method