I've made a class that extends JFrame
, and in my classes constructor, to set the title I can either use:
super("title");
setTitle("title");
or just create a JFrame
object i.e:
JFrame f = new JFrame("title);
How does the compiler differentiate from all of these to conclude the same thing? I know super is used to call overridden methods in the superclass, but how does it specifically know to call the setTitle
method?
My idea is that super calls the constructor of JFrame
class, and there is only one constructor which takes a string parameter, so it's basically doing:
JFrame f = new JFrame("title);
, without explicitly creating the object.
Is this true? If not, can someone explain what super is exactly doing, and why setTitle
does not need an object reference?
Cheers
new JFrame( "title" )
callsJFrame
's constructor. It may callsetTitle()
(but it probably doesn't), or it may just set the internal variable used to hold the title.super.setTitle()
is just a method call. If you have overriddensetTitle()
, it'll ignore your definition and call the same method on the super class. It's normally used for "chaining" to a super class's methods.super( "title" )
can only be called as the first line of a constructor. It is not a method call. It calls a specific constructor in the super class, constructs that object, then continues with your constructor code. This is the way all constructors work. If you don't specify a constructor, the no-argument constructor (super()
) is called automatically.