0009this关键字

this关键字

1、this.属性

在这里插入图片描述
为什么会使用到this
我们看下面这个例子
在这里插入图片描述
在这里插入图片描述
正确写法到底是哪边加this呢?
在这里插入图片描述
当成员变量和局部变量没有同名的时候this可加可不加
在这里插入图片描述
在这里插入图片描述

2、this.方法:没有非用不可的时候

在这里插入图片描述

3、this()或者this(实参列表)

在这里插入图片描述
直接调用this();
在这里插入图片描述
在这里插入图片描述
this(实参列表)实例:
在这里插入图片描述
最后贴上代码吧

package com.atguigu.test01;
/*
 *this 
 *1、意思:当前对象
 *(1)如果它在构造器当中出现,那么我们就说它是 
 *	正在被创建的对象
 *(2)如果它是出现在方法当中,那么我们就说它是
 *	正在调用该方法的对象
 * 
 * 疑问,以前我们没有this不也能正常访问属性吗?为什么要有this呢?
 * 
 * 2、用法
 * (1)this.属性
 * 当局部变量与成员变量同名的时候,可以在成员变量的前面加this.
 * (2)this.方法
 *  没有非用不可的时候
 *  (3)this()或者this(实参列表)
 *  this()表示调用本类的无参构造函数
 *  this(实参列表)表示调用本类的有参构造函数
 *  this()或者this(实参列表)必须在构造器的首行
 */
public class TestThis {
	public static void main(String[] args) {
		Circle c1 = new Circle(1.2);
		Student s1=new Student("张无忌",16,'男',97);
/*		Circle c2=new Circle();
		c2.setRadius(1.2);
		System.out.println(c2.getRadius());*/
	}

}
class Circle{
	//属性
	private double radius; //这是成员变量
	//无参构造器 
	public Circle(){
		System.out.println("一个圆对象被创建");
	}
	//有参构造器
	public Circle(double radius){//这个 radius 是局部变量 是用来给成员变量赋值的
		this();
		this.radius=radius;
		
	}
	//get和set
	public void setRadius(double r){
		this.radius=r;
	}
	public double getRadius( ){
		return radius;//没有同名的情况可加可不加
	}
	public double getArea(){
		return 3.14*radius*radius;//这里也是加不加this都行
	}
}
class Student{
	private String name;
	private int age;
	private char gender;
	private int score;
	
	public Student(){
		
	}
	public Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	public Student(String name,int age,char gender,int score){
		/*this.name=name;
		this.age=age;*/
		this(name,age);//调用上面的有参构造
		this.gender=gender;
		this.score=score;
	}
}











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值