Scenario:
[Updated] A class Creditor can be of an Org or Personnel type. A creditor can be of type A, type B or type C. Here type A is Org, and type B is Personnel. I want to know how I might implement this in the best Java-ish way.
- Have both classes implement an interface and have this third class be an instance of the interface these classes implement. (use Interface as a type)
OR
- Have a generic class, so that I can instantiate any class I want ? (Use generic class )
Which is more preferred or are they totally different thing ? What am I missing? Also explanations.
I have the following two classes Org and Personnel.
public class Org implements Entity{
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public Org(String name){
this.setName(name);
}
}
public class Personnel implements Entity{
private String name;
private String phoneNumber;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public void setPhoneNumber(){..}
public Personnel(String name){
this.setName(name);
}
}
The interface Entity that both the above classes implement"
interface Entity{
String getName();
}
Case 1 and Case 2 codes are below.
Case 1.
Here, third class named Creditor can be an Org or a Personnel, so I have added an Entity interface as type, to reference this class Creditor to either Org or Person objects.
public class Creditor{
public Entity entity;
public Creditor(Entity entity){
this.entity = entity;
}
public static void main(String[] args){
Org o = new Org("Name");
Creditor c = new Creditor(o);
Personnel p = new Personnel("AJ");
Creditor c1 = new Creditor(p);
}
}
OR
Case 2.
Instead of using Interface, why don't I just use generic type box and instantiate as per wish what object I want, like for example Personnel or Org.
public class Creditor<T> {
private T t;
public Creditor(T t){
this.t = t;
}
public static void main(String[] args){
Org o = new Org("Name");
Personnel p = new Personnel("AJ");
Creditor<Org> c1 = new Creditor<>(o);
Creditor<Personnel> c2 = new Creditor<>(p);
}
}
Creditor
can use? Create more and more constructors? Use case 2 and change your class topublic class Creditor<T extends Entity>
.Creditor
, we can't grive you an answer. @Tom: There is only duplicated code if you don't write aCreditor(Entity)
constructor.