Overriding User Library Classes in Java

2019-04-15 00:35发布

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?

2条回答
一夜七次
2楼-- · 2019-04-15 00:50

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.

查看更多
3楼-- · 2019-04-15 01:05

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
    }
}
查看更多
登录 后发表回答