Search code examples
javaclassstaticapplet

How is setForeground method called without creating instance in java?


I was looking at an applet code and it struck me.

My Questions:

why is setForeground() used without an object here despite it being defined as a non-static method in the API

the code is as follows:

import java.applet.Applet;
import java.awt.*;
/*<applet code = "swings.class" height = "500" width = "500"></applet>*/

public class Swings extends Applet{
    public void init(){
        setBackground(Color.yellow);
        setForeground(Color.red);
        Font f = new Font("Comic Sans MS",Font.BOLD,25);
        setFont(f);
    }
    public void paint(Graphics g){
        g.drawString("Welcome to Applets",100,100);
    }
}

Solution

  • setForeground is declared as public in Component, Swings is a subclass of Component,

    enter image description here

    which means setForeground will be inherited by Swings as its own class member, so you can call setForeground in Swings directly.

    You can check jls for more details.

    update

    In java, if both non-static methods are in the same class, they can call each other directly, without creating a new instance.

    Since setForeground is inherited by Swings, setForeground and init are both members of class Swings. So you can call setForeground in init directly.