温馨提示×

温馨提示×

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

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

java Super超类怎么用

发布时间:2026-10-06 07:03:41 来源:亿速云 阅读:97 作者:小樊 栏目:编程语言

在 Java 里,你说的 “Super 超类” 一般有两层常见含义,我分开讲,并配上例子,方便理解。


一、super 关键字(最常问的)

super 用于 子类访问父类 的成员(变量、方法、构造方法)。

1️⃣ 调用父类构造方法

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

class Dog extends Animal {
    Dog() {
        super("小狗"); // 必须放在第一行
    }
}

✅ 注意:

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

2️⃣ 调用父类方法

class Animal {
    void eat() {
        System.out.println("动物吃东西");
    }
}

class Dog extends Animal {
    void eat() {
        super.eat(); // 调用父类方法
        System.out.println("狗吃骨头");
    }
}

3️⃣ 访问父类成员变量

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
    }
}

二、“超类(Superclass)”本身的概念

超类 = 父类(被继承的类)

class Animal {  // 超类 / 父类
}

class Dog extends Animal { // 子类
}
  • Animal 是 Dog 的 superclass
  • 子类可以:
    • 继承父类非 private 成员
    • 重写父类方法
    • 通过 super 访问父类

三、常见易错点 ⚠️

❌ super 不能用于 static 方法
❌ super() 必须在构造方法第一行
❌ 不能调用父类的 private 成员


四、一句话总结

super 是子类用来“找父类”的钥匙;超类就是被继承的类。

如果你愿意,我可以:

  • 用 UML 图画给你看
  • 结合 面试常问点讲
  • 或针对你写的代码具体改 ✅
向AI问一下细节

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

AI
助
手