gumenimeda
gumenimeda

Reputation: 835

Interface, abstract class or another approach java

I have objects Res1 and Res2.

public class Res1 {
    public String foo1;
    public String foo2;
}   

public class Res2 {
    public String foo3;
    public String foo4
}

I also have an object Response

public class Response {
    public ResMsg res;
    public String code;
    public String error;
}

Res1 and Res2 need to be of type ResMsg.

Should I create an empty abstract class

public abstract class ResMsg {

}

and have both Res1 and Res2 extend this class, or should I create an empty interface and then
have them implement this interface.

Having an empty interface or an abstract class seems like an odd thing. What is the best way to do this?

Edit

I am working on a web service that is passing data from one web service to another. In order to better troubleshoot end to end issues I want to create a common Response that will encapsulate responses like Res1 and Res2 (original responses that I am getting from the back-end), and add fields code and error.

Upvotes: 0

Views: 81

Answers (2)

Qiang Jin
Qiang Jin

Reputation: 4467

As in your question, Res1 and Res2 need to be type ResMsg, which suggests Res1, Res2 should have something in common.

But from your class definition of Res1, Res2, they just have different fields and nothing in common.

Whether to use interface or not is based on how you want the Response object to be used.

In my opinion, there will be an interface ResMsg, which defines public api, Res1 and Res2 can directly implement the interface. And if Res1 and Res2 have some common logics, you can have an abstract class, such as AbstractResMsg, to implement the common logics. Res1, Res2 can extend the abstract class and implement the interface.

Upvotes: 0

Leo
Leo

Reputation: 6570

You must create an abstract class only if you want that class to have methods that will be reused by the classes that extends it. If you just want to say that a class belongs to a certain type, I think the use of an interface is more appropriate. This is what we call "tag interface" http://c2.com/cgi/wiki?TagInterface

Upvotes: 1

Related Questions