栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java之super关键字

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java之super关键字

super是java中的一个关键字

super关键字两种语法
1.super.;
2.super();

不使用super关键字
代码如下:

//父类
public class A {
    int x;
   void eat(){
        System.out.println("我是A里的");
    }
}
//子类
public class B extends A{
    void eat(){
        System.out.println("我是B里的");
    }
}


public class Super {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        a.eat();
        b.eat();
    }
}

输出如下:

我是A里的
我是B里的

Process finished with exit code 0

使用super的话,代码如下:

//父类
public class A {
    int x;
    public A(int x) {
    }
   void eat(){
        System.out.println("我是A里的");
    }
}
//子类
public class B extends A{
    B(int x){
        super(x);
    }
    @Override
    void eat() {
      super.eat();
    }
}


public class Super {
    public static void main(String[] args) {
        A a = new A(3);
        B b = new B(4);
        a.eat();
        b.eat();
    }
}

输出如下:

我是A里的
我是A里的

可以看到,子类B中的eat方法使用super关键字来对父类中的eat方法进行重写(重写:http://t.csdn.cn/3z27C)

注意事项:
如果子类想使用父类的构造方法,必须在子类的构造方法中使用且必须使用关键字super,而且super必须是子类构造方法的第一条语句

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/840881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号