Home  >  Article  >  Java  >  Sample code sharing of Java keyword this

Sample code sharing of Java keyword this

黄舟
黄舟Original
2017-03-16 09:50:281435browse

The role of this:

1) this is a reference to the current object, which facilitates the use of the current object parameters;

2) You can return a reference to the object's own class, and you can also call another constructor

## in a

constructor #this example:

public class ThisDemo {    
public ThisDemo()
    {        
    this.number=20;    
    }    
    public ThisDemo(int number,int number2)
    {        
    this();//调用无参数的构造函数        
    this.number2=number2;    
    }
    ThisDemo increment(){
        number++;        
        number2++;        
        return this;    
        }    
        private void print(){
        System.out.println("number="+number+";number="+number2);    
        }    
        public static void main(String[] args) {
        ThisDemo tt=new ThisDemo();        
        tt.increment().increment().increment().print();    
        }
}

The above is the detailed content of Sample code sharing of Java keyword this. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn