简体   繁体   中英

Java2D method call without class

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) or componentInstance.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?

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.

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