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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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
}
}