一、super 关键字的特点:
1.super 和 this 关键字的特点类似 super 代表的是父类对象的引用
2.当子父类的成员出现同名时 可以通过 super 来区别
3.子类的构造方法中 通过super 关键字调用父类的构造方法
强调:
当构造一个子类对象的时候一定会先调用父类的构造方法来构造父类的对象
调用父类构造方法的语句必须是子类构造方法中的第一条指令。
二、代码:
package jicheng.heavysea.java;
class Person
{
String name;
int score;
//public Person(){}
public Person(String name,int score)
{
this.name = name;
this.score = score;
}
public void peat()
{
System.out.println("人吃饭!");
}
public void pdrink()
{
System.out.println("人喝水!");
}
}
class Student extends Person
{
public Student(String name,int score)
{
super(name,score); //调用父类的构造方法
System.out.println("子类只能调用父类的构造方法!");
}
void gotoschool()
{
System.out.println("去上学!");
}
public void peat() //子父类的成员出现重名 通过super来区分
{
super.peat(); // 调用父类
System.out.println("eat!!!!");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Person("heavy",99);
//p.peat();
//若只new一个子类对象 父类构造方法会先于子类构造方法调用
Student s = new Student("sea",100);
s.peat();
}
}