-1

I've read a lot of explanations for the use of keyword 'this' in java but still don't completely understand it. Do i use it in this example:

private void login_BActionPerformed(java.awt.event.ActionEvent evt) {                                        
    if(user_TF.getText().equals("admin")&& pass_PF.getText().equals("admin")){
        this.B.setVisible(true);
    }else{
        JOptionPane.showMessageDialog(null, "Warning!", "InfoBox: "+"Warning", JOptionPane.INFORMATION_MESSAGE);
    }
    this.user_TF.setText("");
    this.pass_PF.setText("");
}      

It's supposed to open a new window if a user and pass match. Do i use 'this' keyword anywhere here?

mojic2D
  • 31
  • 1
  • 6

2 Answers2

1

I think there are two main usages you should know:

  • If you have a class variable with name N, and a method variable with name N, then to distinguish them, use this.N for class variable and N for method variable. Screenshot displaying possible usage
  • Imagine you have 2 constructors. One takes String name, another takes name + age. Instead of duplicating code, just use this() to call another constructor. Another screenshot displaying the usage

In your case, I don't see any LOCAL (method) variables of name 'B', so I guess you can do without it.

Cargeh
  • 1,029
  • 9
  • 18
0

Any non static method of the class needs an object of that class to be invoked. Class has the blueprint of the state and behavior to modify and read the state. Object is the realization of this blueprint. Once object is created , it has those states and methods.

Suppose you have below code.

public class A{
    int property;
    public void foo(){
         bar();
    }

    public void bar(){
         property = 40;
    }
}

public class B{
    public static void main(String[] args){
        A obj = new A();
        obj.foo();
    }
}

Lets try to answer few questions.

Q1. Inside the mwthod foo we invoke bar , we have not used any explicit object to invoke it (with . dot operator), upon which object is the method bar invoked.

Q2. Method bar tries to access and modify the variable named property. Which object does this state called property belong to ?

Answers

A1. Object referred by A.this (it is same as this) . It is the object which has invoked foo method which is implicitly made available insode the called method. The object upon which execution of the method takes places can be accessed by this.

A2. same as answer to Q1.

The object at anytime can be accessed by Classname.this inside the non static methods or blocks of the class.

nits.kk
  • 5,204
  • 4
  • 33
  • 55