java关键字super

java关键字super

super用来引用直接父类对象,每当创建子类的实例时,父类的实例被隐式创建,由super关键字引用变量引用
1,用法
①引用直接父类的实例变量,调用直接父类方法

class Animals{
    String color = "red";
    void output(){
        System.out.println("this is father......");
    }
}
class Dog extends Animals{
    String color = "green";
    void output(){
        System.out.println("this is son.......");
        super.output();//调用父类方法
        System.out.println(color);
        System.out.println(super.color);//引用父类变量

    }

}
    public class ex {
        public static void main(String[] args) {
           Dog dog = new Dog();
           dog.output();
        }
    }

运行结果

this is son.......
this is father......
green
red

我觉得super调用直接父类的方法有种撤销子类函数覆盖的意思,函数覆盖之后想要是被覆盖了的父类函数显现出来,用到super关键字
②引用直接父类的构造函数

class Animals{
    Animals(){
        System.out.println("Father's constructor");
    }
}
class Dog extends Animals{
    Dog(){
        super();//若果没有这行代码,编译器也会自动的添加上
        System.out.println("Son's constructor");

    }

}
    public class ex {
        public static void main(String[] args) {
           Dog dog = new Dog();
        }
    }

运行结果

Father's constructor
Son's constructor

Process finished with exit code 0

当创建一个子类实例的时候,一定会隐式的创建一个父类实例,既然创建了父类实例,就一定得调用父类的构造函数,所以上例的super();可写可不写,但注意,写了必须放在子类构造函数的第一行。
2,小实例应用
体会一下super的用法

class Student{
    String name;
    int id;
    Student(int id,String name){
        this.name = name;
        this.id = id;
    }
}
class MiddleStudent extends Student{
    int grade;
    MiddleStudent(int grade,int id,String name) {
        super(id,name);//此行代码必须要有
        this.grade = grade;
    }
}
    public class ex {
        public static void main(String[] args) {
           MiddleStudent s = new MiddleStudent(8,1234,"Mary");
           System.out.println(s.grade+" "+s.name+" "+s.id);
        }

    }

结果

8 Mary 1234

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值