July 28, 2016

Method overriding example in java

Method overriding example in java


Description

In method overriding, the sub class and super class contains the same function with type and signature.
The function in the subclass overrides the funtion in the super class at the run time.This is a runtime polymorphism. The class must be in Is-A relation ship ie, Clerk is a emloyee , sweeper is a employee. Note: static methods cannot be overriden, because static methods are bound with class, we class static method using class name and not by the objects, so we cannot override public static void main().

Source code

/**
 *
 */
package oops;

/**
 * @author java programs
 *
 */
public class Employees {

int name;
int age;
int salary;

int getSalary(){
return 15000;
}

}





/**
 * 
 */
package oops;

/**
 * @author java programs
 *
 */
public class Clerk extends Employees {
int getSalary(){
return 20000;
}

}


/**
 * 
 */
package oops;

/**
 * @author java programs
 *
 */
public class HumanResource extends Employees {
int getSalary(){
return 35000;
}

}


package oops;

public class Sweeper extends Employees {
 int getSalary(){
return 5000;
 }
}

/**
 * 
 */
package oops;

/**
 * @author java programs
 *
 */
public class MethodOverriding {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Employees employee = new Employees();
System.out.println("This is employee class : "+employee.getSalary());
employee = new Clerk();
System.out.println("This is clerk class : "+employee.getSalary());
employee = new HumanResource();
System.out.println("This is human resource class : "+employee.getSalary());
employee = new Sweeper();
System.out.println("This is sweeper class : "+employee.getSalary());
System.out.println(" Method overriding example in java");

}

}


Output



Method overriding example in java

Similar posts


http://javabelazy.blogspot.in/

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments