简体   繁体   中英

Remove methods or fields from class that extends swing component

Asking out of curiosity...

Suppose we have a class that extends Jpanel. And we don't need all the Jpanel methods. For example we are not going use any ToolTipText on the new class, so we don't need the setToolTipText method. My question is: Is it possible to remove the methods we don't need from the new class? If yes, does it make any difference to execution speed (faster construction maybe)?

Is it possible to remove the methods we don't need from the new class?

If you want to hide part of the interface from the user of the class, then you shouldn't be using inheritance . Remember, inheritance is for an is-a relationship, and if subclass A is a JPanel , then it certainly has use for ToolTip . What you should use is Composition , which allows you to mask part of the composed objects methods.

public class A
{
    public void wantedMethod() {}

    public void unwantedMethod() {}
}

If I wanted to hide unwantedMethod from my subclass, I could do something like this:

public class B
{
    private A a;

    public void wantedMethod() {
        a.wantedMethod();
    }
}

This will not allow unwantedMethod to escape into the interface of class B .

Is it possible to remove the methods we don't need from the new class?

  • Yes it's possible, but be careful, there are differences between adding any Listener to plain JPanel (any method(s) is/are removed) and adding Listener to JPanel where the Listener was removed, notifiers are modified

  • Can't find real reason, can be counterproductive, but very different situation will be in case that you want to modify built in listeners, notifiers, accelerators

  • all methods addXxxXxx implemented in API are possible to remove (valid for JPanel , could not be valid for all compound JComponents )

If yes, does it make any difference to execution speed (faster construction maybe)?

  • I'd doubt it, everything depends on method(s) that is/are forced from listeners (your customizations, your code)

If the method is never called, then there is no difference to the execution speed of the class. Removing the methods would decrease in compilation time, but would be negligible.

It is not possible, and the number of methods does not affect the execution speed. Theoretically, loading a class with fewer methods, will not take as long, but it's just a few bytes and thus only a few microseconds, and the method IS there in the first place, anyhow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM