0

I have two Java classes that both have the same method (the foo method in the example), like:

public class Class1 {

    private String var = "HELLO";

    public String getString() {
        return foo(var);
    }   

    private int foo(String s) {
        return s.hashCode();
    }
}


public class Class2 {

    private String var = "WORLD";

    public String getString() {
        return foo(var);
    }   

    private int foo(String s) {
        return s.hashCode();
    }
}

The method foo is the same, it change only the parameter I use with it.

So is it better create a superclass with the foo method and two subclass or create an interface? I am not so sure about the interface, because I will write again the code in the two classes.

Some advice?

  • It's not possible to answer given the context you provide. Use a superclass if it represents something truly common in the purpose of both `Class1` and `Class2`. Don't do that if there is no conceptual relationship between the two classes. – Jim Garrison Feb 03 '17 at 23:37
  • 1
    Looks like it could be a `static` method on a _completely different_ `class`. Don't abuse inheritance where it makes no sense. I see no reason why `Class1` and `Class2` should be related by inheritance. – Boris the Spider Feb 03 '17 at 23:38

0 Answers0