super关键字有点像this关键字,但this只能用于构造方法中,而super不仅用于继承中,也能用于构造方法中,可简化代码
class Animal{
String name="动物";
void shout(){
System.out.println("动物发出的叫声");
}
}
class Dog extends Animal{
String name="犬类"; //重写了父类的成员变量
void shout(){
super.shout();//访问了父类的成员方法shout()
}
void printName(){
System.out.println("name="+super.name);//如果不是用super,这里得到的值应该是重写的name:犬类,但是用了supper,则会是:动物
}
}
public class Example14{
public static void main(String[] args){
Dog dog= new Dog();
dog.shout();//调用的是父类的打印“动物发出的叫声”
dog.printName();//虽然子类重写了父类成员变量,但由于super关键字的存在,这里仍是“动物”
}
}
//在构造方法中的使用
class Animal{
public Animal(String name){ //构造方法,方法名与类名同,有参
System.out.println("我是一名"+name);
}
public Animal(){//无参的构造方法
System.out.println("我是一名惭愧的人");
}
}
class Dog extends Animal{
public Dog(){
super("惭愧书生");//通过super可调用构造方法并传入参数。必须在第一行,并且只能出现一次
}
/*public Dog(){
}*/ //这么写会默认调用无参的构造方法,结果就是无参的结果
}
public class Example15{
public static void main(String[] args){
Dog dog=new Dog();//构造方法实例化直接会调用方法,打印结果
}
}