2020/06/16学习笔记(this关键字)

this关键字的作用

  1. 如果存在同名的成员变量和局部变量,在方法内部默认访问的是局部变量,因为java采取的是就近访问的原则,可以通过this指定访问成员变量数据。
  2. 当一个方法中只存在成员变量,而没有局部变量的时候,编译器会在这个变量前加上this关键字,使得该方法(函数)能够使用调用该方法的对象中的成员变量。
  3. this关键字代表了其所属函数的调用者对象。
  4. 在一个构造函数中调用另一个构造函数初始化对象。但是需要注意以下问题:
    this关键字调用其它构造函数时,this语句必须位于构造函数中的第一个语句
    this关键字在构造函数中不能出现相互调用的情况,否则会产生死循环
class Student
{
    String name;
    int age;

    public Student(String name, int age)
    {
        //this.name = name;
        this(name); // 调用了本类中只有一个参数的构造函数
        this.age = age;
        System.out.println("两个参数的构造方法被调用了");
    }

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

}

public class thisTest1
{
    public static void main(String[] args)
    {
        Student s = new Student("铁蛋", 10);
        System.out.println("小孩叫:" + s.name + ", 今年" + s.age + "岁");

    }
}

/*结果:一个参数的构造方法被调用了
两个参数的构造方法被调用了
小孩叫:铁蛋, 今年10岁*/
class Animal
{
	String name = "狗";
	String color;
	public void eat(){
		String name = "老鼠";
		System.out.println(name + "在吃...");  // "老鼠在吃..."
	}
}
/*eat()函数先在本程序块中查找是否有name变量,如果找到,比如name="老鼠",就不会再去堆内存中查找。*/
class Demo
{
	public static void main(String[] args)
	{
		Animal a = new Animal();
		a.eat();	
	}
}

// 结果:老鼠在吃...

局部变量和成员变量调用说明
如果想要改成“狗在吃…”,只要如下这样改:

class Animal
{
	String name = "狗";
	String color;
	public void eat(){
		String name = "老鼠";
		System.out.println(this.name + "在吃...");  // "狗在吃..."
	}
}
/*eat()函数先在本程序块中查找是否有name变量,如果找到,比如name="老鼠",就不会再去堆内存中查找,
如果在程序块中出现"this.name",程序就会去堆内存中查找对象中的name变量。*/
class Demo
{
	public static void main(String[] args)
	{
		Animal a = new Animal();
		a.eat();	
	}
}
class Student
{
	String name;
	int age;
	
	public Student(String name, int age)
	{
		name = name; // 此处相当于是局部变量给局部变量赋值,而成员变量并没有获得赋值
		age = age;
	}
	
}

class Demo
{
	public static void main(String[] args)
	{
		Student s = new Student("铁蛋", 10);
		System.out.println("小孩叫:" + s.name + ", 今年" + s.age + "岁");
		// 所以这里的成员变量s.name(String类型)仍然是初始值null,而s.age的初始值是0
	}
}
//结果:小孩叫:null, 今年0岁

public Student(String name, int age)
	{
		this.name = name; // 这样写就没问题了,this.name就是指的成员变量
		this.age = age;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值