Reputation: 117
I'm sorry, maybe it's simple, but I can't explain this. There is following code(swing):
public class Sandbox2 extends Frame implements ActionListener {
JTextField tf; JLabel l; JButton b;
Sandbox2() {
tf=new JTextField();
...
//there is what i can`t understand
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
...
}
public static void main(String[] args) {
new Sandbox2();
}
}
Firstly I create a button, text field and others, after that I add it to a frame. But how it works if all methods, add(), setSize()... were called without frame instance?
I understand that it due with a Frame inheritance, but how?
Upvotes: 0
Views: 284
Reputation: 2228
The class SandBox2
extends JFrame
meansSandBox2
is-a JFrame
class. The SandBox2
class inherits the following methods from the super class JFrame
. Hence can be called like add(b)
add(b);
add(tf);
add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
As per the Doc As a convenience add
and its variants, remove
and setLayout
have been overridden to forward to the contentPane as necessary. This means you can write: frame.add(child);
SandBox2
uses inheritance by which class allows to inherit the features(fields and methods) of another class. The subclass can add its own fields and methods in addition to the superclass fields and methods.
Upvotes: 0
Reputation: 77187
All of these calls are happening inside the context of an instance. If you just call setSize
, then that is the same as saying this.setSize
. (If you tried to call setSize
in a static method, which specifically means that it is not linked to a specific instance, then you would get an error.)
Upvotes: 4
Reputation: 11832
When you construct an instance of a class that extends another class, the parent constructor is called first, setting up anything that it needs, before your local constructor is called (either implicitly, or by calling super()
in the first line of your constructor).
So, since Sandbox2
is-a JFrame
(extends the class), the JFrame
stuff will be ready by the time the code in your Sandbox2
constructor is executed.
Upvotes: 0