Method Overriding
Method
overriding : When Subclass acquires the properties of
Super class through method then it is Method
Overriding
Method Overriding in java is most useful features
of java. Through inheritance we can reuse already existed code and through
method overriding we can modify that reused code according to our requirements
Method Overriding Rules:-
- must be IS-A relationship
(inheritance).
- method must have same name as
in the super class
- method must have same parameter
as in the super class.
- The return type of the overrided method must be
compatible with super class method. If super class method has primitive
data type as its return type, then overrided method must have same
return type in sub class also. If super class method has derived or user
defined data type as its return type, then return type of sub class method
must be of same type or its sub class
- You cannot reduce the visibility of overloaded method in
subclass.
Note- You
cannot override static method in method overriding.because static method is related with class and method name with object.
dynamic/late binding polymorphism: overriding
public class Bank {
int getRateOfInterest()
{
return 4;}
}
class PNB extends Bank{
int getRateOfInterest(){return 9;}
}
class KENRA extends Bank{
int getRateOfInterest(){return 6;}
}
class HDFC extends Bank{
int getRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){
PNB pnb=new PNB();
KENRA kenra=new KENRA();
HDFC hdfc=new HDFC();
System.out.println("PNB Rate of Interest: "+pnb.getRateOfInterest());
System.out.println("KENRA Rate of Interest:
"+kenra.getRateOfInterest());
System.out.println("HDFC Rate of Interest:
"+hdfc.getRateOfInterest());
}
}
OutPut-:
PNB Rate of Interest: 9
KENRA Rate of Interest: 6
HDFC Rate of Interest: 9
|
.
.
No comments:
Post a Comment