When to use which?
- If there is an IS-A relation, and a class wants to expose all the interface to another class, inheritance is likely to be preferred.
- If there is a HAS-A relationship, composition is preferred.
Some cases we required some properties of one class not fully we cannot use interfaces, here is one simple example
public class InheritanceTest {
public static void main(String args[]) {
Person p = new Employee();
System.out.println(p.getAge());
System.out.println(p.getPersonCountry());
}
}
class Person {
public int getAge() {
return 1;
}
public String getPersonCountry() {
return "INDIA";
}
}
class Employee extends Person {
public int getAge() {
return 2;
}
}
Here is if we want to change Employee getAge return type it will not allow, see below error.
In this type of situation we can use the composition e.g.:
public class CompositionTest {
public static void main(String args[]) {
Employee1 p = new Employee1();
System.out.println(p.getAge());
System.out.println(p.getPersonCountry());
}
}
class Person1 {
public int getAge() {
return 1;
}
public String getPersonCountry() {
return "INDIA";
}
}
class Employee1 {
public String getAge() {
return "2";
}
public String getPersonCountry() {
Person1 p1 = new Person1();
return p1.getPersonCountry();
}
}
0 comments:
Post a Comment