0

I have tried to find existing similar problems on stack overflow already to no avail. I have a Parent class that I do not have access to modify. It has a public method A inside it that calls its own private method B. Private method B has some logic in it that I need to override. So I've created a child class which extends the Parent class. My hope was that if my overridden parentMethodA calls super.parentMethodA(), it would reference the child class version of parentPrivateMethodB with the modified logic instead of the parent class version. However, when I run the below, super.parentMethodA() runs the version of the private method B that is in the parent class instead. Hopefully I clarified the issue well enough. Is there a way to fix this to where it will call the Child class version of private method B? I want to avoid reproducing all the logic in parentMethodA inside the overridden version with an explicit call to Child class private method B. That is why i was trying the "super" notation. The pseudo-code is below.

public class Child extends Parent
{
  @Override
  public Results parentMethodA(String param)
  {
    return super.parentMethodA(param);
  }

  public void parentPrivateMethodB(String param)
  {
    //modified logic here
  }

}

Niko
  • 67
  • 1
  • 4
  • Private methods are not subject to overriding. – khelwood Jun 25 '21 at 18:19
  • I didn't override a private method. i made my own copy of it. – Niko Jun 25 '21 at 18:22
  • You basically can't do this without access to the source code of `Parent`. The whole point of private methods like this is "hands off." You can't change it. You'll need to get access to the code you say you don't have. – markspace Jun 25 '21 at 18:22
  • So this cannot be done even with Reflection? – Niko Jun 25 '21 at 18:23
  • You want to call a method as declared in your superclass and have it instead run the matching method in your subclass. That's what overriding means. – khelwood Jun 25 '21 at 18:24
  • Even with reflection I don't think this works. With reflection you could call a private method. Reflection won't make a method call a method it isn't calling. – markspace Jun 25 '21 at 18:39

0 Answers0