温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Super超类如何调用

发布时间:2026-10-06 05:55:36 来源:亿速云 阅读:88 作者:小樊 栏目:编程语言

在 Java 中,“Super 超类”通常指父类( superclass ),而 super 关键字用来在子类中调用父类的内容。下面从常见用法给你系统讲一下。


一、super 能调用什么?

在子类中,super 可以用来:

  1. 调用父类构造方法
  2. 调用父类成员变量
  3. 调用父类成员方法

二、调用父类构造方法(最常见)

语法

super(参数列表);

注意

  • 必须写在子类构造方法的第一行
  • 如果不写,Java 会默认调用 super()(父类无参构造)

示例

class Animal {
    Animal(String name) {
        System.out.println("Animal: " + name);
    }
}

class Dog extends Animal {
    Dog() {
        super("Dog"); // 调用父类构造方法
        System.out.println("Dog created");
    }
}

三、调用父类成员变量

当子类成员变量与父类重名时使用:

class Parent {
    int x = 10;
}

class Child extends Parent {
    int x = 20;

    void show() {
        System.out.println(x);      // 20
        System.out.println(super.x); // 10
    }
}

四、调用父类方法

当子类重写了父类方法时使用:

class Parent {
    void say() {
        System.out.println("Parent say");
    }
}

class Child extends Parent {
    void say() {
        super.say(); // 调用父类方法
        System.out.println("Child say");
    }
}

五、常见错误

❌ 不能在 static 方法中使用 super

static void test() {
    super.x; // 错误
}

❌ super() 不在构造方法第一行

Child() {
    System.out.println("hi");
    super(); // 错误
}

六、总结一句话

super 就是“找父类”:构造用 super(),变量用 super.x,方法用 super.method()

如果你有具体代码场景(比如抽象类、接口、构造冲突),可以贴出来我帮你改。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手