温馨提示×

java中super什么意思

小亿
91
2024-09-13 14:24:20
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,super关键字用于引用父类(超类)的一个对象。它主要有两种用途:

  1. 访问父类的成员变量(尽管这通常被认为是不良的编程实践,因为它破坏了封装性):
class Parent {
    int x = 10;
}

class Child extends Parent {
    int x = 20;

    void printBothX() {
        System.out.println("Child x: " + x);
        System.out.println("Parent x: " + super.x);
    }
}
  1. 调用父类的成员方法或构造方法:
class Parent {
    void printHello() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent {
    void printHello() {
        System.out.println("Hello from Child");
    }

    void callParentPrintHello() {
        super.printHello(); // 调用父类的printHello()方法
    }
}
  1. 在子类构造方法中调用父类的构造方法:
class Parent {
    Parent(String message) {
        System.out.println(message);
    }
}

class Child extends Parent {
    Child() {
        super("Hello from Parent's constructor"); // 调用父类的构造方法
    }
}

总之,super关键字在Java中用于访问和操作父类的成员和方法。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java中super是什么意思

0