Home > Java > JavaBase > body text

Does java this access member variables?

Release: 2019-11-22 14:23:03
Original
3481 people have browsed it

Does java this access member variables?

If there are member variables and local variables with the same name, the data of the local variable is accessed by default inside the method. You can specify the data of the member variable to be accessed through the this keyword . In one constructor, you can call another constructor to initialize the object.

1. Use the this keyword in the method definition of the class to represent the reference of the object using the method

2. Use this## when it is necessary to indicate who is the object currently using the method.

#3. Sometimes this can be used to deal with the situation where the member variables and parameter variables in the method have the same name

4.This can be regarded as a variable, and its value is a reference to the current object

Note:

When there are member variables and local variables with the same name, the local variables are accessed inside the method (Java adopts the "proximity principle" mechanism to access. ) If a variable is accessed in a method and the variable only exists as a member variable, the Java compiler will add the this keyword in front of the variable.

/*
this关键字调用其他的构造函数要注意的事项:
    1. this关键字调用其他的构造函数时,this关键字必须要位于构造函数中 的第一个语句。
    2. this关键字在构造函数中不能出现相互调用 的情况,因为是一个死循环。

*/ class Student{ int id; //身份证 String name; //名字 //目前情况:存在同名 的成员 变量与局部变量,在方法内部默认是使用局部变量的。 public Student(int id,String name){ //一个函数的形式参数也是属于局部变量。 this(name); //调用了本类的一个参数的构造方法 //this(); //调用了本类无参的 构造方法。 this.id = id; // this.id = id 局部变量的id给成员变量的id赋值 System.out.println("两个参数的构造方法被调用了...");
    } public Student(){
        System.out.println("无参的构造方法被调用了...");
    } public Student(String name){ this.name = name;
        System.out.println("一个参数的构造方法被调用了...");
    }

}


class Demo7 
{ public static void main(String[] args) 
    {
        Student s = new Student(110,"铁蛋");
        System.out.println("编号:"+ s.id +" 名字:" + s.name); /*

        Student s2 = new Student("金胖子");
        System.out.println("名字:" + s2.name);
    */ }
}
Copy after login

For more java knowledge, please pay attention to

java basic tutorial.

The above is the detailed content of Does java this access member variables?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template