简体   繁体   中英

Java interface best practice

I have two objects in the following way

public class ObjectA {
 int id ;
 String name;
}

 public class objectB {
  Long id;
  String name;
 }

I want to be able to create an interface 'AnObject' that will be implemented by these two objects. How would this interface look like?

public interface AnObject {
  public <type?> getId() ;
  public String getName();
}

What should the type be in the getter for ID?

First of all, do not name it Object . Object is Java's implicit base class for all other classes. Technically, you could name your interface Object as long as you do not place it in the package java.lang , but that would be highly misleading.

To provide different return types for getId() in ObjectA and ObjectB , use generics:

public interface MyObject<T> {
  T getId();
  String getName();
}

public class ObjectA implements MyObject<Integer> {
  @Override
  public Integer getId() {
    return 0;
  }

  @Override
  public String getName() {
    return "A";
  }
}

public class ObjectB implements MyObject<Long> {
  @Override
  public Long getId() {
    return 0;
  }

  @Override
  public String getName() {
    return "B";
  }
}

If getId() always returns a number, you could also define MyObject as MyObject<T extends Number> . Note that you cannot use the native types int and long with generics; you have to use the boxed types Integer and Long .

Assuming that your id is always a number.

If the user of your getter getId() doesn't (or shouldn't) care for the actual type of the return value you could also use Number directly, without generics. It depends on the context if you want to use generics or not. An advantage of not using generics in this case would be that you don't have to define the actual type of the id, which makes the calling code less coupled with the implementation of MyObject .

public interface AnObject {
    public Number getId() ;
    public String getName();
}

The code that calls this, will not know the actual type of the Id. However they can still be sure that it is a number and can call things like Number.doubleValue() or Number.longValue() as the calling code requires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM