user1112789
user1112789

Reputation: 437

Avoid multiple definitions of a class for different types containing the same method

I have 2 classes as such:

public class A {
    private String label;

    public String getLabel() {
        return label;
    }
}

public class B {
    private String label;

    public String getLabel() {
        return label;
    }
}

Then I have another class where I want to access these classes' label values:

public class C {
    private String label;

    public C(A object) {
        label = object.getLabel();
    }
}

For example, the above definition only works for A. I want to be able to pass either A or B to C's constructor. The closest thing I can think of is to make C a generic class but then I lose access to getLabel(). How can I go on about this? I feel like this is a basic design pattern but since I'm new to Java, I don't know where to start. Any help is greatly appreciated.

Upvotes: 1

Views: 455

Answers (2)

Anderson Vieira
Anderson Vieira

Reputation: 9059

You could create an interface and make both A and B implement it:

interface HasLabel {
    String getLabel();
}

Then

public class A implements HasLabel { ... }

public class B implements HasLabel { ... }

And in C:

public class C {
    private String label;

    public C(HasLabel object) {
        label = object.getLabel();
    }
}

When you do C(HasLabel object) you guarantee that getLabel() can be called on the argument, so it allows you to do object.getLabel().

Upvotes: 5

isnot2bad
isnot2bad

Reputation: 24464

It's very simple in Java using inheritance and polymorphism:

This is an abstract base class that implements the common behaviour:

public abstract class Base {
    private String label;

    public String getLabel() {
        return label;
    }
}

A and B are subclasses of Base and inherit their behaviour:

public class A extends Base {
    // specific fields / methods of class A
}

public class B extends Base {
    // specific fields / methods of class B
}

You can now use instances of A and B in C using the base type Base:

public class C {
    private String label;

    public C(Base object) {
        label = object.getLabel();
    }
}

E.g.:

A a = new A();
B b = new B();

C c1 = new C(a);
C c2 = new C(b);

Upvotes: 2

Related Questions