super一般用于在继承方面中父类的子类中使用。
第一种
super.xxx;(xxx为变量名或对象名)
这种方法意义为,获取父类中的名字为xxx的变量或方法引用。
使用这种方法可以直接访问父类中的变量或对象,进行修改赋值等操作
第二种
super.xxx();(xxx为方法名)
这种方法意义为,直接访问并调用父类中的方法。
第三种
super();
这种方法意义为,调用父类的初始化方法,其实就是调用父类中的public xxx()方法
例子;
public class Animal {
String name;
int age;
double height;
public Animal(){
}
public Animal(String name,int age,double height){
this.name=name;
this.age=age;
this.height=height;
}
}
public class Cat extends Animal{
String furColor;
double weight;
//所有现象的根本原因就是:我必须先创建父类,并且只能创建一个父类。
public Cat(){
super();//调用父类空构造器,默认不写
}
public Cat(String furColor){
super();//必须放在第一行
this.furColor=furColor;
}
public Cat(String furColor,double weight){
// super();
// this.furColor=furColor;
this(furColor);//第一行只能存在super构造器或者this构造器
this.weight=weight;
}
//其实我就是在实现方法调用方法,只是这个方法特殊,是一个构造器
public Cat(String name,int age,double height,String furColor,double weight){
// this.name=name;
// this.height=height;
// this.age=age;
super(name,age,height); //调用了父类的有参构造器之后,super()就不会默认给我分配了。
this.furColor=furColor;
this.weight=weight;
}
}