重拾JAVA基础05——this关键字

package day07;
/*
 *存在同名的成员变量与局部变量时,在方法内部访问的是局部变量(java 采取的是就近原则) 
 * 
 * this 关键字:
 *  this 关键字代表了所属函数的调用者对象。
 *  this 关键字作用:
 *  	1.如果存在同名成员变量与局部变量时,可以通过this访问指定成员变量的数值。
 * 		2.可以在一个构造函数中调用另一个构造函数初始化对象。
 * this 关键字注意事项:
 * 		1.存在同名的成员变量与局部变量时,在方法内部访问的是局部变量(java 采取的是就近原则) 
 * 		2.如果在一个方法中,访问了一个变量,该变量只存在成员变量的情况下,那么java编译器会在该变量的前面添加this关键字。
 * 		3.this关键字在构造函数中不能出现相互调用,因为是个死循环。
 */

class Animal{
	String name ;//成员变量
	
	String color;
	
	public Animal(String name,String color){
		this.name = name ;
		this.color = color;
		
	}
	
	public void eat(){
		
		System.out.println(name+" is eating...");
	}
	
}

public class Demo6 {

	public static void main(String[] args) {
		Animal a = new Animal("dog","baise");
		a.eat();
		Animal b = new Animal("cat","heise");
		b.eat();
	}

}

package day07;

class Student {
	int id ;
	
	String name;
	
	public Student(int id, String name){//一个函数的形式参数,属于局部变量。
		this(name);//调用了本类的一个参数的构造方法。 必须是第一个执行的语句。
		System.out.println(" 两个参数的构造方法调用了...");
		this.id = id;
//		this.name = name;
		//如果在这里能调用到下面一个参数的构造方法时,那么该问题可以解决,减少重复代码。
		//this(name);写在后面编译不会通过,不符合语法。
	}
	public Student(String name ){

		System.out.println("一个参数的构造方法调用了...");
		this.name = name ;
	}
	public Student(){
		System.out.println(" 无参数的构造方法调用了...");
	}
}


public class Demo7 {
	
	public static void main(String[] args) {
		Student s = new Student(110,"tzsad");
		System.out.println(s.id+s.name);
//		Student s2 = new Student("124211421");
//		System.out.println(s2.name);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值