总结java中的super和this关键字

知识点:

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

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

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

              关于子类实例化过程中的内存分配,在下一篇博客中说明一下(https://www.cnblogs.com/shuaifing/p/10684485.html)

一: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修饰属性,引用父类的属性
当子类与父类的属性同名时,通过“super.属性”显示地调用父类中声明的属性
调用子类的同名属性,使用“this.属性”
//动物
public class Animal{
public String gender="男";//性别

public Animal(){
this.name="张三";
System.out.println("动物无参构造函数!");
}
}
//人
public class Person extends Animal {
public Person(){
super.gender="女";//子类无参构造函数中,调用父类的属性,并修改父类的gender属性
System.out.println("人无参构造函数!");
}
}
(2)super修饰构造方法,引用父类的构造方法
一般在子类中使用“super(形参列表)”来显示地调用父类中的构造方法
a.在构造方法内部,super(形参列表)必须申明在首行
b.在构造方法内部,因为this(形参列表)也必须声明在首行,所以this(形参列表)或者super(形参列表),只能出现一个
c.当子类构造器中,不显地调用“this(形参列表)”或者super(形参列表)其中任何一个,默认调用的是父类的空参构造函数
//生物
public class Creature {
public Creature(){
//进入到Creature类的无参构造函数后,首先会调用父类Object的无参构造函数(object中隐藏了)
//super()无参的构造函数,不写的话,默认有的

System.out.println("生物无参构造函数!");
}

}
//动物
public class Animal extends Creature{
public Animal(){
super();//进入到Animal类的无参构造函数后,首先会调用父类Creature的无参构造函数,实例化父类Creature实例
System.out.println("动物无参构造函数!");
}

}
//人
public class Person extends Animal {
public Person(){
super();//进入到person类的无参构造函数后,首先会调用父类Animal的无参构造函数,实例化父类Animal实例
System.out.println("人无参构造函数!");
}
}
//测试类
public class Test {
public static void main(String[] args) {
Person p=new Person();//初始化p实例时,会调用Person类的无参构造函数
}
}
 

运行结果:

 (3)super修饰成员方法,引用父类的成员方法
当子类重写父类的方法后,在子类中,想显示地调用父类中被重写的方法,可以使用“super.方法”
//动物
public class Animal extends Creature{

//展示动物属性方法
public void showInfo(){
System.out.println("展示动物属性方法");
}
}
//人
public class Person extends Animal {
//展示人类属性方法
@Override
public void showInfo(){
     System.out.println("展示人类属性方法");
super.showInfo();

}

}
 
原文地址:https://www.cnblogs.com/shuaifing/p/10682628.html