Method Overriding in Java Example 2

Java Programming Language / Class, Object and Methods in java

16053

Program:

 class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{
int getRateOfInterest(){return 9;}
}

class ICICI extends Bank{
int getRateOfInterest(){return 10;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 11;}
}

class MethodOverriding{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Output:

SBI Rate of Interest: 9
ICICI Rate of Interest: 10
AXIS Rate of Interest: 11
Press any key to continue . . .

Explanation:

The above code shows an example of method overriding in Java. There is a base class Bank that contains a method getRateOfInterest() which returns 0. Then, there are three derived classes SBI, ICICI and AXIS that inherit the Bank class and override the getRateOfInterest() method with their own implementation. The SBI class returns 9, the ICICI class returns 10 and the AXIS class returns 11.

In the main method, objects of the three derived classes are created and their getRateOfInterest() methods are called, which returns the interest rate specific to each bank. The output of the program displays the interest rate for each bank.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.