I just started to learn Java and tried to draw some rectangles.
I have run this example and can't understand one thing: class ShapesDemo2D has a constructor:
public void init() {
//Initialize drawing colors
setBackground(bg);
setForeground(fg);
}
I understand that setBackground
is a method.
- But how can it be called without a class or instance reference?
This is a method of an abstract Component class in Component.java file.
- Shouldn't it be like
Component.setBackground(bg)
orcomponentInstance.setBackground(bg)
?
But Component is an abstract class, so it can't be instantiated, and it's methods can not be called.
- So how it is possible to call this method?
CodePudding user response:
You're forgetting ShapesDemo2D extends JApplet
at the top of the class code which means that the class extends another class, JApplet, and so the code in the method above above is effectively calling super.setBackground(bg);
and super.setForeground(fg);
. The super class, JApplet has these methods since as per the JApplet API, the class extends from Component which has these methods, meaning that ShapesDemo2D will have inherited the methods as well.
Having said this, please ditch this tutorial since applets are no longer support, are dead technology and have been dead for the longest time, and there is no sense learning a dead technology.
Side note, you state:
class ShapesDemo2D has a constructor:
public void init() { //Initialize drawing colors setBackground(bg); setForeground(fg); }
But this is in fact not a constructor but rather a method. A constructor for the ShapesDemo2D class would look like:
public ShapesDemo2D() {
// .....
}
This may seem like a pedantic distinction, but programming is all about being as accurate as possible with your thinking and your code. The Java compiler is strict and unforgiving, and so you must be as well.