dimanche 21 août 2022

What's the best way to write classes that are only different in some attributes?

public interface I {
    // ...
}

public class A {
    String name = "A";

    public String toString() {
        return "It is " + name;
    }

    // other methods... (might be different)
}

public class B {
    String name = "B";

    public String toString() {
        return "It is " + name;
    }

    // other methods... (might be different)
}

Like the example above, I have 2 identical class that are only different in the name attribute (and maybe some other methods). I want to extract the toString method to an interface or an abstract class and give it a default implementation. How can I do that?

Aucun commentaire:

Enregistrer un commentaire