Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How do I add to a base class without modifying class file

I am using a Java library that has a class hierarchy:

e.g. classes C1 and C2 that both extend class B

Is there a way for me to add functionality (attributes, methods) to class B such that it will be available to the child classes C1 & C2 without modifying the 3 files?

If not, what is the right way to do this short of rewriting all 3 classes?

like image 694
GroovyDotCom Avatar asked Oct 29 '25 09:10

GroovyDotCom


1 Answers

Assuming you aren't able to modify B for some reason, make an intermediary class that extends it for you:

public class ClassC extends ClassB {

    //additional functionality

}

Then it's simple:

public class Class1 extends ClassC {...}

If you can modify B, the other classes already inherit the methods, and you don't need to worry about rewriting them unless you mark the methods abstract

like image 126
Rogue Avatar answered Oct 31 '25 12:10

Rogue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!