一、this关键字
(1)调用类中的属性(2)调用类中的方法或构造方法;如下所示调用类中的属性:
案例一:
public class text10{
public static void main(String[] args){
Person p1 = new Person();
p1.setName ("张三");
p1.setAge (12);
}
}
class Person{
private String name;
private int age;
//对外提供一个为 name属性设值的方法
public void setName(String name){ //这里的name也就是上面的张三;
this.name = name; //后面的name指的是本类的name,就近原则;
//this.name是当前对象的name,即上面的P1.name,谁调用了这个方法谁就是当前对象
}
//对外提供一个为name属性取值的方法:
public String getName(String name){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(int age){
return age;
}
}
案例二:
/*
this只能使用在实例方法和构造方法中,谁调用实例方法,this就是谁;
this.大部分情况下是可以省略的;
this.不能出现在static静态方法中。。
*/
public class test02 {
public static void main(String[] args){
cost c1 = new cost("张三");
c1.Shopping();
cost c2 = new cost("里斯");
c2.Shopping();
}
}
class cost{
private String name;//实例变量
public cost(String name){
this.name = name;
}
public void setName(String x){
this.name = x;
}
public String getName(){
return name;
}
//实例方法
public void Shopping(){
//c1调用Shopping(),this就是c1;
//c2调用Shopping(),this就是c2;System.out.println(this.name+"正在购物");
System.out.println(name+"正在购物");
}
}
二、super和this关键字
1、super、this是一个关键字,全部小写。 2、super和this对比着学习。
-
this:
this能出现在实例方法和构造方法中。
this的语法是:"this."、"this()"
this不能使用在静态方法中。
this.大部分情况下是可以省略的。
this.什么时候不能省略呢? 在区分局部变量和实例变量的时候不能省略。 如下所示:
public void setName(string name){
this.name =name;
}
this()只能出现在构造方法第一行,通过当前的构造方法去调用“本类"中其它的构造方法,
目的是:代码复用。
-
super:
super能出现在实例方法和构造方法中。
super的语法是:"super."、"super( )"
super不能使用在静态方法中。
super,大部分情况下是可以省略的。 super.什么时候不能省略呢????????
- 父类 和子类中有共同的属性特征或者方法时,如果想在子类中访问”父类的特征“,super.不能省略。。
super()只能出现在构造方法第一行,通过当前的构造方法去调用“父类"中 的构造方法,
目的是:创建子类对象的时候,先初始化父类型特征。
this和super关键字大总结
this关键字
super关键字: