Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interface best practice

Tags:

java

interface

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?

like image 737
user_mda Avatar asked Jul 16 '15 13:07

user_mda


People also ask

Should you use interfaces everywhere?

It is only a good thing where you need it, and bad everywhere else. If you are using an interface on a place where should be high cohesion, then you are doing it wrong. Every interface has a cost and a value, if you are not considering it and blindly make them everywhere, then you are doing it simply wrong.

Why should we code to interface in Java?

Why code to interfaces? The Java interface is a development contract. It ensures that a particular object satisfies a given set of methods. Interfaces are used throughout the Java API to specify the necessary functionality for object interaction.

Why interface is not in Python?

Interfaces are not natively supported by Python, although abstract classes and abstract methods can be used to go around this. At a higher perspective, an interface serves as a template for class design. Interfaces create methods in the same way that classes do, but unlike classes, these methods are abstract.

Why do we use interfaces?

Interfaces are useful for the following: Capturing similarities among unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class.


1 Answers

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.

like image 134
Robin Krahl Avatar answered Sep 20 '22 00:09

Robin Krahl