JAVA“this“关键字的用法

JAVA"this"关键字的用法

1.在类的方法中,使用this关键字代表的是调用此方法的对象的引用

class Student{
	int age;
	Student(int n){
		age=n;
	}
	void printage(){
		System.out.println(this.age);
	}
}
public class This{
	public static void main(String[] args){
		Student stu=new Student(18);
		stu.printage();
		
	}
}

2.this可以看作一个变量,它的值是当前对象的引用

class Student{
	int age;
	Student(int n){
		age=n;
	}
	void printAge(){	
		System.out.println(this.age);
	}
	void newObject(){
		Student stu2=null;//新实例化一个对象stu2
		stu2=this;//stu2等于当前对象的引用
		stu2.printAge();
	}
}
public class This{
	public static void main(String[] args){
		Student stu1=new Student(18);
		stu1.newObject();
	}
}

3.this方法可以处理方法中的成员变量和形参同名问题

class Student{
	int age;
	String name;
	
	Student(int age,String name){
		this.age=age;//形参与成员变量同名,age=age? no no no,this.age=age;
		this.name=name;
	}
	void printAgeName(){	
		System.out.println("name:"+name+"\nage:"+age);
	}
	void newObject(){
		Student stu2=null;
		stu2=this;
	}
}
public class This{
	public static void main(String[] args){
		Student stu1=new Student(18,"小明");
		stu1.printAgeName();
	}
}

4.在一个构造方法中调用另一个构造方法

class Student{
	int age;
	String name;
	String sex;

	Student(String name){
		this.name=name;
		System.out.println("第一个构造方法\nname="+this.name);
	}
	Student(String name,int age){
		this.age=age;
		this.name=name;
	}
	Student(String name,int age,String sex){
		this("小红");//在第三个构造方法中调用第一个构造方法,注意只能在最前面一排调用,且只能调用一个构造方法.
		this.age=age;
		this.name=name;
		this.sex=sex;
	}
	void information(){
		System.out.println("name:"+name+"\nage:"+age+"\nsex:"+sex);
	}
}
public class This{
	public static void main(String[] args){
		Student stu1=new Student("小明",18,"男");
		stu1.information();
	}
}


版权声明:本文为SCT_CX原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。