Thursday, June 30, 2016

Is- A Relationship

By using extends keyword we can implemented Is- A Relationship. Its also known as Inheritance. The main advantage of Is -A relationship is code reusability.

we can understand  Is - A relationship  from given example.

class P{
public void m1(){
 System.out.println("parent");
}
}

class C extends P{
public void m2()
{
System.out.println("child");
}
}
class Test{
public static void main(String[] args){
P p=new P(); // case 1
p.m1();
//p.m2();// Compile time error: can not find symbol: method m2 at location Class P
C c=new C(); // case 2
c.m1();
c.m2();

P p1=new C(); // case 3
p1.m1();
//p1.m2(); // Compile time error: can not find symbol: method m2 at location Class P

//C c1=new P(); //case 4
// CE : incompatible types found: P required C. mismatch



}
}


Conclusion:

1. Parents reference can be use to hold child objects but by using that reference we can not call child    specific methods but we can call methods present in parent class

2. Parent reference can be use to hold child object but child reference can not be use to hold parent      object.

3. if in a program we have some common methods(code redundancy)  then we should go for inheritance.

4. by using inheritance we can reduce time and cost.

<<       >>