Java中的this关键字有什么用呢?我们知道用类名定义一个变量的时候,定义的只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法,那一个类如何引用来访问自己的属性和方法呢?这就是this关键字的作用,它可以在类里面来引用这个类的属性和方法。我们具体来看一下。
一、Java中this有什么用呢?
Java中的this关键字主要有三个应用:
(1)this调用本类中的属性,也就是类中的成员变量;
(2)this调用本类中的其他方法;
(3)this调用本类中的其他构造方法,调用时要放在构造方法的首行。
二、Java中this作用的示例代码
①Java中this调用本类中的属性
public class ThisDemo {
String name="Mick";
public void print(String name){
System.out.println("类中的属性 name="+this.name);
System.out.println("局部传参的属性="+name);
}
public static void main(String[] args) {
ThisDemo tt=new ThisDemo();
tt.print("Orson");
}}
②Java中this调用本类中的其他构造方法
public class ThisDemo {
String name;
int age;
public ThisDemo (){
this.age=21;
}
public ThisDemo(String name,int age){
this();//调用时要放在构造方法的首行
this.name="Mick";
}
private void print(){
System.out.println("终名字="+this.name);
System.out.println("终的年龄="+this.age);
}
public static void main(String[] args) {
ThisDemo tt=new ThisDemo("",0); //随便传进去的参数
tt.print();
}}
this调用本类中的其他方法的方式类似,只是没有放到首行的限制条件
热点新闻