[SOLVED] how to force the children method arguments to extend specific class for multiple methods in java – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Babak

I have an interface:

public interface Parent{
  Integer method1(Payment payment);
  Integer method2(Invoice invoice, Payment payment);
}

And I have multiple kinds of classes that extends Payment and Invoice class, let’s say PaymentType1, InvoiceType1 and PaymentType2, InvoiceType2 are my children classes of Payment and Invoice.

Now, I want to create two classes that extend Parent in a way to force child classes to just use the extended class of Payment and Invoice. For example something like this:

First:

public class ChildType1 extends Parent{
  public Integer method1(PaymentType1 payment){...}
  public Integer method2(InvoiceType1 invoice, PaymentType1 payment){...}
}

Second:

public class Child2 extends Parent{
  public Integer method1(PaymentType2 payment){...}
  public Integer method2(InvoiceType2 invoice, PaymentType2 payment){...}
}

what kinds of solutions can I use to resolve it?



Solution

It looks like an XY-problem.

You’ve designed your classes in such a way that you can’t benefit from Polymorphism and instead using Payment and Invoice types you need to discriminate between their subtypes (like PaymentType1, PaymentType2).

And that impedes implementing the contract of the Parent interface. Attempts of loosening the constraints of the contract would not solve the actual the problem caused by the design flow.

The contract defined by Parent is fine.

The problem is rooted on the level of subclasses PaymentType1/PaymentType2 and InvoiceType1/InvoiceType2 which doesn’t respect the Liskov substitution principle because you’re unable to use them in place of Payment and Invoice.

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

That where you can find the room for improvement.


This Question was asked in StackOverflow by Babak and Answered by Alexander Ivanchenko It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?