meghanath ch
meghanath ch

Reputation: 93

common method and method body with one changing method parameter

We have a common method as below:

public class CommomClass()
{
    public String[] commonMethod(Object1 inputObject1)
    {
        String[] output;

        output[0] = (inputObject1.getValue1());
        output[1] = (inputObject1.getValue2());

        return output;
    }
}

The same method can be used in other classes by changing the method parameter to Object2 inputObject2. How do we accomplish this without redundant code?

Upvotes: 0

Views: 77

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55233

The classes Object1 and Object2 could implement an interface:

public interface HasValues {

    public String getValue1();
    public String getValue2();
}

And your common method could be redefined to take an instance of that interface:

public String[] commonMethod(HasValues hasValues) {

    String[] output = new String[2];

    output[0] = hasValues.getValue1();
    output[1] = hasValues.getValue2();

    return output;
}

Upvotes: 4

Related Questions