目录
super关键字简介
super关键字表示超类,用来指向父类对象。super关键字有以下三种用法
- super可以指向父类的实例变量
- super可以调用父类方法
- super可以调用父类构造函数
super可以指向父类的实例变量
public class superinstacne {
public static void main(String[] args) {
Dog dog = new Dog();
dog.printColor();
}
}
class Animal{
String color = "white";
}
class Dog extends Animal{
String color = "blcak";
void printColor() {
System.out.println(color); //打印的是子类Dog类的变量
System.out.println(super.color); //打印的是父类Animal类的变量
}
}
super可以调用父类方法
public class supermethod {
public static void main(String[] args) {
Dog1 dog1 = new Dog1();
dog1.eat();
dog1.annimaleat();
}
}
class Animal1{
void eat() {
System.out.println("Animal eat...");
}
}
class Dog1 extends Animal1 {
//子类重写继承的eat方法
void eat() {
System.out.println("Dog eat...");
}
void annimaleat() {
//调用父类的eat方法
super.eat();
}
}
super可以调用父类构造方法
public class superlearn {
public static void main(String[] args) {
Emp emp = new Emp(1, "yasuo");
emp.display();
}
}
class Person{
String name;
int id;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Emp extends Person{
Emp(int id, String name){
super(id, name); //通过super调用父类的构造方法,同时必须放在第一行
}
void display() {
System.out.println(id);
System.out.println(name);
}
}