Overriding java methods happen in a case where a child class implements a method that is contained in super class.The main use of overriding is to provide a new implementation of a method.
Contents
Overriding Java methods can take place if only:-
- Child class and parent class are in IS-A inheritance.
- Child class method should have the same name as parent class.
- Child class method should have the same parameters as the parent class.
Overriding Java methods Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<textarea class="java" cols="10" name="code" rows="10">public class Mammals {//Parent class void giveBirth()//public method giveBirth { System.out.println("All Mammals give birth to Young Ones"); } } //Inner class class Lion extends Mammals//Child class { void giveBirth()//Overriding giveBith Method { System.out.println("Lion gives bith to calves"); } public static void main(String args[]) { Lion lion=new Lion();//Creating a new Lion class lion.giveBirth();//Calling giveBirth method. } } </textarea> |