java-面向对象-关键字this详解

关键字this详解


public class This01 { 

	//编写一个main方法
	public static void main(String[] args) {

		Dog dog1 = new Dog("大壮", 3);
		System.out.println("dog1的hashcode=" + dog1.hashCode());
		//dog1调用了 info()方法
		dog1.info(); 

		System.out.println("============");
		Dog dog2 = new Dog("大黄", 2);
		System.out.println("dog2的hashcode=" + dog2.hashCode());
		dog2.info();
	}
}

class Dog{ //类

	String name;
	int age;
	// public Dog(String dName, int  dAge){//构造器
	// 	name = dName;
	// 	age = dAge;
	// }
	//如果我们构造器的形参,能够直接写成属性名,就更好了
	//但是出现了一个问题,根据变量的作用域原则
	//构造器的name 是局部变量,而不是属性
	//构造器的age  是局部变量,而不是属性
	//==> 引出this关键字来解决
	public Dog(String name, int  age){//构造器
		//this.name 就是当前对象的属性name
		this.name = name;
		//this.age 就是当前对象的属性age
		this.age = age;
		System.out.println("this.hashCode=" + this.hashCode());
	}

	public void info(){//成员方法,输出属性x信息
		System.out.println("this.hashCode=" + this.hashCode());
		System.out.println(name + "\t" + age + "\t");
	}
}

内存图解

请添加图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值