6

Let say I have three classes:

class A
{
    public void method()
    { /* Code specific to A */ }
}

class B extends A
{
    @Override
    public void method()
    { 
       /*Code specific to B*/
       super.method(); 
    }
}

class C extends B
{
    @Override
    public void method()
    { /* I want to use the code specific to A without using B */ }
}

The goal in this case is to use the code from A without using the code from B. I thought there was a way to do it by calling the super method, but this brings in the code from B as well.

Is there a way to do this?

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
eBehbahani
  • 1,579
  • 5
  • 19
  • 41
  • 1
    I don't think there is a language construct to do this, but you can do it with a little refactoring. – khelwood Nov 17 '14 at 18:26
  • 3
    The immediate question I have from yours is, "Why?" If you don't want to use what happens in `B`'s constructor then why does `C` extend `B` and not `A`? When you have issues like this you need to step back and reexamine if your approach is really the most clear and intuitive. – Brandon Buck Nov 17 '14 at 18:28
  • Sorry, not constructor but method. Same difference though, the same question still applies. – Brandon Buck Nov 17 '14 at 18:33
  • 1
    The reason I am asking is the framework I use for the application I am building has classes that inherit several times. I cannot make changes directly to those classes, but I need to access a method from a super class while not using the code from intermediate super classes. If that makes sense. – eBehbahani Nov 17 '14 at 18:42

3 Answers3

2

The short answer is no. What you're seeing is that your design is flawed. It indicates that you need too move the code in class A out into a helper class. B and C would then use it via composition. You could try using partials to get the behavior you want. See this link for more details. Partial function application in Java 8

Community
  • 1
  • 1
Virmundi
  • 2,497
  • 3
  • 25
  • 34
2

You could instantiate an object of class A in C and call the method method

class C extends B
{
    @Override
    public void method()
    { /* I want to use the code specific to A without using B */ 
    A test = new A();
    test.method();
    }

}

Not sure if this is what you meant. Also asumed you forget the method name method in class A.

Roy Wasse
  • 390
  • 1
  • 10
1

No there is no way to do it. You can simply create another method in class B that executes the code of A's method, and call that method in subclass C.

M A
  • 71,713
  • 13
  • 134
  • 174