Java basics Use of this 10.13

Source: Internet
Author: User

This
1. Returns a reference to the object that called the current method.
public class leaf{
private int i=0;
Public Leaf increament () {
i++;
return this;
}
public static void Main (string[] args) {
Leaf x= New Leaf ();
X.increment (). print ();
Leaf y= New Leaf ();
Y.increment (). print ();
}
}

This represents an instance of the leaf class when executing x.increment (), this represents a reference to instance X. Similarly executes y.increment (), which represents a reference to instance Y.

2. Call the other constructor methods of the current class in the constructor method.
Defines the construction method of the 3 person class, which is no parameter, has a parameter, has two parameters, implements the code reuse, uses this () and this (_name) to invoke person () and person (String _name)
When you use this to invoke other constructor methods, you must place them at the beginning of the construction method and no I will not compile
public class person{
private String name;
private int age;
Private String sex;
Public person () {
sex= "Male";
}
Public person (String _name) {
This ();
Name=_name;
}
Public person (String _name,int _age) {
This (_name);
Age=_age;
}
}
3. When the method parameter name and member variable name are the same, it is used to distinguish parameter names from member variables.
The parameter name of the setter method is the same as the member variable name, this.name represents the member variable name, and name indicates the parameter name.
public class person{
private String name;
privae int age;
public void SetName (String name) {
This.name=name;
}
public void Setage (int.) {
This.age=age;
}
}

Java basics Use of this 10.13

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.