Method overriding in Java occurs when a subclass or child class defines a method that is the same as the parent class.
Method overriding is one of the way by which Java achieve Run Time Polymorphism.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Earth extends Planet { public static void hide() { System.out.println("The hide method in Earth."); } public void override() { System.out.println("The override method in Earth."); } public static void main(String[] args) { Earth myEarth = new Earth(); Planet myPlanet = (Planet)myEarth; myPlanet.hide(); myPlanet.override(); } } class Planet { public static void hide() { System.out.println("The hide method in Planet."); } public void override() { System.out.println("The override method in Planet."); } } |