Based on some stackoverflow post:
Java does not support multiple inheritance.
There are a few workarounds I can think of:
The first is composition: make a class that takes those two activities as fields.
The second is to use interfaces. // This is my question
I try constructing a class that can have AA class's method and BB class's method through interface or composition. I read a lot about inheritance vs composition, but my question is interface vs composition (which one is better). If I want to use these two classes methods in a single class Preference,
class AA{
public int id(){
return 0;
}
}
class BB{
public String name(){
return "0";
}
}
Obviously, Java does not support multiple inheritance and we need to use either interface or composition.
Interface:
First Construct interfaces that corresponds to these two classes:
interface AAInterface{
public int id();
}
interface BBInterface{
public String name();
}
then construct a Preference class that implements those two interfaces, and declared two class objects inside that class:
class Preference implements AAInterface, BBInterface{
AA aa;
BB bb;
public int id() {
return aa.id();
}
public String name() {
return bb.name();
}
}
Composition: Directly construct a class that has two fields that corresponds to two class objects in order to use their methods.
class Preference{
AA aa;
BB bb;
public int id() {
return aa.id();
}
public String name() {
return bb.name();
}
}
As a result, in the Preference class, by using other interface or composition method, I can use the id() method and the name() method which derived from AA class and BB class.
Question: Why should we use interface since composition is way simpler and better? Are there any reason that we should use the interface instead of composition? To put it differently, how to get two classes methods in a single class using java interface, is my way the correct way to do that?