Answering this question: How to GUI - Using paintcomponent() to initialize a GUI and then to add GUI based on mouse I've stated this:
You don't override
paintComponent()
properly. This is a protected method, not public. If you add@Override
annotation on this method then the compiler will complain.
But @peeskillet wisely pointed out this:
The compiler will not complain about
public
orprotected
withpaintComponent
. You can override with a higher visibility but not a lower one.public
is higher thanprotected
so there's no problem.
Which is certainly true. But now it arises this question: Is it good practice override with a higher visibility?
Link to JComponent.paintComponent() javadoc.
Image of Netbeans not complaining at all:
One reason to do this is if you have a method you need to override elsewhere in your project and the current scope does not allow you to. Typically when using default instead of protected.
By creating a new sub class in the right package elsewhere in your project with revised scope, you can then create an anonymous class in your code where you need it as you are now allowed to override the troublesome method instead of having to do with reflection (which makes for quite unreadable code).
This is also a reason for library classes never to be final because then you cannot do things like this.
EDIT: I was asked to elaborate on why this is relevant for Dependency Injection. I can only speak based on my own experiences, first with Guice and now with Dagger.
Dagger uses Constructor Injection which basically mean that a class will get all its dependencies provided as arguments to the constructor (and only there) and that the glue code binding this together is listed in a Dagger @Module. In this module it is usually very convenient to return a subclass of a library class augmenting with log statements or providing a custom toString() method. In order to actually DO this without reflection tricks the clasess cannot be final and you need to be able to override methods and to use fields in the superclass directly. Hence no final classes and both types need to be at least protected
instead of private
!
(and I can strongly recommend using Dagger because it moves the dependency resolving in the java compiler giving the IDE the information needed to help you resolve problems at compile time, instead of depending on magic in the runtime in the wild. I am still amazed at the insight in the Java ecosystem the Dagger designers had to even get this idea and then realize it)