I code java with BlueJ for Mac. I have added the stdlib.jar library (From princeton http://introcs.cs.princeton.edu/java/stdlib/). Before added this library I had my own class named StdDraw.java (The specific class I was using on the project) and copy/pasted the code. I also adjusted some of the code and added some new lines. Since I cannot edit the libraries code, how may I override or extend library classes to add additional functionality?
Since the library classes are final
, you can't extend them. Another option is to wrap them in your own classes. For example, you can create your own drawing class that has an instance of StdDraw
that it delegates to. For many of your methods you can simply call the corresponding method of the StdDraw
instance, or you can simulate overriding by implementing methods yourself.
Just simply extend the class,
public MyClass extends ClassFromLib
make sure the library jar file is on the classpath. If the author of that class declared it as final indicating that it's not suitable for subclassing. then the best alternative is to use the delegate pattern.
I wrote the code below in this editor so no promises that it complies, but hopefully you get the idea.
public Myclass {
private ClassFromLib cfl = new ClassFromLib();
public void methodA(){
//Do whatever you need here
cfl.methodA(); //Doesn't have to be the same name.
//Do whatever you need here
}
}
来源:https://stackoverflow.com/questions/11909419/overriding-user-library-classes-in-java