谈谈java中的super和this关键字

知识点:

             在java类中使用super引用父类的成分,用this引用当前对象

              this可以修饰属性、构造器、方法

              super可以修饰属性、构造器、方法

一:this关键字

  this可以修饰属性、构造器、方法;用this引用当前对象

  (1)this修饰属性,调用类的属性

//set方法
public void setName(String name) {
this.name = name;
}

//有参数构造函数
public Person(String name){
this.name=name;
}

(2)this修饰构造器,在构造器中通过 this(形参)的方式显示地调用本类中,其他重载的指定的构造器(在构造器内部必须声明在首行
public Person(){
System.out.println("调用当前类的无参构造函数");
}
public Person(String name){
this();//调用本类中无参构造函数
this.name=name;
}

public Person(String name,int age){
this(name); //在构造器中通过 this(形参)的方式显示地调用本类中,其他重载的指定的构造器(在构造器内部必须声明在首行)
this.age=age;
}
(3)this修饰成员方法,调用类的方法
public void showInfo(){
System.out.println("调用当前类的成员方法showInfo");
}
public void showAllInfo(){
this.showInfo();
System.out.println("调用当前类的成员方法showAllInfo");
}

二:super关键字

super可以修饰属性、构造器、方法;用super引用父类的成分

(1)super修饰属性,引用父类的属性
//动物
public class Animal{
public String gender="男";//性别

public Animal(){
this.name="张三";
System.out.println("动物无参构造函数!");
}
}
//人
public class Person extends Animal {
public Person(){
super.gender="女";//子类无参构造函数中,调用父类
System.out.println("人无参构造函数!");
}
}
 
 
 

猜你喜欢

转载自www.cnblogs.com/shuaifing/p/10682628.html