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?
-
you could override it but super method will still existdogant– dogant2015-05-18 19:21:04 +00:00Commented May 18, 2015 at 19:21
-
That's sort of what I thought -- you end up with two methods, the one in the superclass and the one in the inheriting class, identical except for the single line of code. But if you could redesign the superclass, there ought to be a way of avoiding code duplication, right?Jeff– Jeff2015-05-18 19:25:32 +00:00Commented May 18, 2015 at 19:25
-
m0skit0 & sodium24 both are correct. But I did not understand why you are looking for this kind of facility?Bacteria– Bacteria2015-05-18 19:25:39 +00:00Commented May 18, 2015 at 19:25
-
Arin: Because there exists a class that does almost what I want that it seems like I should take advantage of by inheriting from it -- it also seems wrong to duplicate the code but there seems to be way around it. Am I wrong?Jeff– Jeff2015-05-18 19:27:39 +00:00Commented May 18, 2015 at 19:27
-
A template method might be helpfulMr Tsjolder from codidact– Mr Tsjolder from codidact2015-05-18 19:29:08 +00:00Commented May 18, 2015 at 19:29
2 Answers
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.
3 Comments
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.