Jeff
Jeff

Reputation: 1591

How to avoid re-using code when using inheritance in Java?

Say there is a class which has a method that is very close to what you want -- only a single line in the method need to change. If you are not allowed to change the superclass, is there any way to inherit from the superclass without copying all the code from the method you want to change?

Upvotes: 2

Views: 102

Answers (2)

Necreaux
Necreaux

Reputation: 9776

Short answer: no

Long answer: maybe in some situations

For example, if a() does something where I can tack on extra behavior at the end, then you can just call it in the new class and then add additional behavior.

@Override
public void a() {
    super.a();
    //  do something else here
}

If there is some line in the middle of super.a() that cannot be executed then you're out of luck. If it is okay to "clean up" the undesired behavior after the fact, then this is possible.

Upvotes: 5

Safwan Hijazi
Safwan Hijazi

Reputation: 2089

It's impossible to do that in inheritance, inheritance means that you extend feature from Parent class and use as it's in child class, and if you override the method from super class so you replaced it. also you can't change parent method as you said, so you should reimplement method again.

I think if you give us more details about the parent class and method, we can help more and find another way to solve your problem.

Upvotes: 0

Related Questions