This is a small example for overriding in java.
Method Overriding : Implementation in sub class with same parameters and type signature Overrides the implementation in super class. Call of overriding is resolved through dynamic binding by JVM. JVM only deals with overriding.
Base class
public class Base {
public void area()
{
System.out.println(" area inside base class ");
}
}
Derived class
public class Derived extends Base{
public void area() {
//super.area();
System.out.println(" area inside derived class");
}
}
Main class
public class Main {
public static void main(String[] args) {
System.out.println(" inside main ");
System.out.println("----------------------------------");
System.out.println("1. Base b = new Base() ");
Base b = new Base();
b.area();
System.out.println("----------------------------------");
System.out.println("2. Derived d = new Derived() ");
Derived d = new Derived();
d.area();
System.out.println("----------------------------------");
System.out.println("3. Base bd = new Derived()");
Base bd = new Derived();
bd.area();
System.out.println("----------------------------------");
}
}
Real world example for the method overriding in java
Description
Source code
public class Employees{
int getSalary(){
return 1000;
}
}
class Clerk extends Employee{
int getSalary(){return 20000;}
}
class HumanResourceManager extends Employee{
int getSalary(){return 50000;}
}
class TeamLeader extends Employee{
int getSalary(){return 75000;}
}
class Developer extends Employee{
int getSalary(){return 95000;}
}
class CheckSalary{
public static void main(String args[]){
Employee e= new Clerk();
System.out.println(" salary : "+e.getSalary());
Employee e= new HumanResourceManager();
System.out.println(" salary : "+e.getSalary());
Employee e= new Developer();
System.out.println(" salary : "+e.getSalary());
}
}
No comments:
Post a Comment
Your feedback may help others !!!