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;
}
}