简体   繁体   中英

What does "this." mean and refer to in Java

I am kind of new to java and wrote an assignment that made a JFrame with a button on it. What exactly does "this.setTitle..." and "this.setSize..." mean. Here is my code:

import javax.swing.JButton;
import javax.swing.JFrame;

public class Assignment1 extends JFrame{
    public Assignment1() throws Exception{
        this.setTitle("Assignment 1");
        this.setSize(400,800);
        this.getContentPane().add(new JButton("Click"));
        this.setVisible(true);
    }
public static void main(String[] args) throws Exception{
    new Assignment1();


 }
}

“this”表示类的一个实例,Assignment1,在本例中是一个专门的 JFrame。

The setTitle, setSize, getContentPane and setVisible are methods of JFrame and they are being inherited by your Assignement1 class.

This this is a reserved word that indicates the instance of the class your are using. When you say this.setTitle, for example, your reference the method setTitle of the current instance of Assignement1 you are using.

Assume you create two instances of Assignment1, like this:

a1 = new Assignment1();
a2 = new Assignment1();

If you say a1.setTitle("alfa") you'll be using the setTitle method of the instance a1. Inside the class you'd refer to this method as this.setTitle, exactly as it is in your class. Then if you say a2.settitle("beta") this won't conflict with the first statement. You'd get two JFrames, one with title "alfa" and the other with title "beta".

This is the reason why you can't use this in static methods. Static methods may be invoked without the need to create an instance of the class. This is why they are also called "class methods".

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