I think that the adapter pattern could be an idea (might not be really this pattern but the idea came from him).
This might be a lot of work just for you example but for more complex work, this is a good approch (personnal opinion of course).
Create an interface an two class that will adapt these function like this :
The originals classes
Class A
public class A {
private int id;
public A(int id){
this.id = id;
}
public int getId() {
return id;
}
}
And the class B
public class B {
private int id;
public B(int id){
this.id = id;
}
public int getId() {
return id;
}
}
Create an interface like :
public interface Adapter {
public int getId();
}
And create both adapters :
Adapter A :
public class AdapterA implements Adapter{
private A a;
public AdapterA(A a){
this.a = a;
}
public int getId() {
return a.getId();
}
}
and Adapter B
public class AdapterB implements Adapter{
private B b;
public AdapterB(B b){
this.b = b;
}
public int getId() {
return b.getId();
}
}
Now if you need to work with this class, just create an adapter and call the getId of these adapter.
Using your example (Class1 = A and Class2 = B)
Adapter adapter = new AdapterA(a); //This mean that you need to create the Adapter when you create (receive the class A or B)
//Adapter adapter = new AdapterB(b);
if (adapter.getId().length() > MAX_LENGTH) {
throw new Exception();
}
If one method have a different name, you just need to update the getter in the specific adapter, the logic behind won't change. So if in B the getId become getIdentity, the only update would be in the adapterB.