As already answered, generic methods in Java do not support this kind of restriction.
If it is possible to change the code of First and Second , then you can take out the methods that method refers to in the common interface / parent class and write one method that accepts this interface.
If this is not possible, then you can try to wrap First and Second into classes that will implement the interface with common methods.
Primitive example for one common method:
class First { //общий метод void save() {...} } class Second { void save() {...} } //создаем интерфейс interface Saveable { void save(); } //класс-обертка для First class FirstSaveableWrapper implements Saveable { private final First first; FirstSaveableWrapper(First first) { this.first = first; } @Overrides public void save() { first.save(); } } //аналогичный класс для Second class SecondSaveableWrapper implements Saveable { ... } //общий метод Ret method(Saveable obj) { ... obj.save(); } //перегруженные методы для First и Second Ret method(First first) { return method(new FirstSaveableWrapper(first)); } Ret method(Second second) { return method(new SecondSaveableWrapper(second)); }
So we will reduce the scale of duplication of the code before calling individual methods. How justified such a struggle with duplication depends on how many First and Second common methods and what is the probability that the logic method will change for both classes / for each class separately.
Depending on the situation, you can replace the explicitly declared wrapper classes with anonymous classes that implement the interface:
Ret method(First first) { return method(new Saveable(first){ void save() { first.save(); } }); }
Or, put each method into a separate interface and use lambda expressions / method references.
methoddoes? Does he refer to some methods common toFirstandSecond? - default locale