Saturday, February 21, 2015

Inheritance

Inheritance, with help of inheritance you can inherit the superclass methods,variables.
Multiple inheritance is not possible in Java instead we can acieve this with interface.
super is used to call the superclass constructor, super.methodname is used to invoke the super call methods.
method overriding - in which the method is overriden in the superclass.
method overloading - if the method signature is changed then it is overloading
final - by using the class or method final it stops inheritance.
Object class is the superclass of all classes.
Follow the below example

InterestCalculation.java
package InheritanceExample;

public class InterestCalculation {
	public int amount;
	public String category;

	InterestCalculation(String category, int amount) {
		this.category = category;
		this.amount = amount;
	}

	void interestratecalculation() {
		System.out.print("For " + this.category + " and for this amount "
				+ this.amount);
	}
}



Adult.java
package InheritanceExample;

public class Adult extends InterestCalculation {
	private int interestrate;
	Adult(String category, int amount){
		super(category,amount);
	}
	
	void interestratecalculation(){
		if(amount<=1000){
			interestrate=8;
		}else{
		  interestrate=9;
		}
		super.interestratecalculation();
		System.out.println(" The interest rate is "+interestrate);
	}

}




Senior.java

package InheritanceExample;

public class Senior extends InterestCalculation {
	private int interestrate;
	Senior(String category, int amount){
		super(category,amount);
	}

	void interestratecalculation(){
		   interestrate=10;
			super.interestratecalculation();
			System.out.println(" The interest rate is "+interestrate);
		}
}



mainClass.java
package InheritanceExample;

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Adult adultobj=new Adult("adult",1000);
		Adult adultobj1=new Adult("adult",1001);
		Senior seniorobj=new Senior("senior",1000);
		
		adultobj.interestratecalculation();
		adultobj1.interestratecalculation();
		seniorobj.interestratecalculation();

	}

}


Output:
For adult and for this amount 1000 The interest rate is 8
For adult and for this amount 1001 The interest rate is 9
For senior and for this amount 1000 The interest rate is 10
>>>
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment