Java 中的 super 用于访问父类的方法和成员变量,主要用途包括调用父类构造函数、访问父类方法和访问父类变量。在子类中使用 super() 调用父类构造函数,super.methodName() 访问父类方法,super.variableName 访问父类变量。注意:super 只能在子类中使用,必须作为语句的第一行。

Java 中的 super
super 在 Java 中是一个关键字,用于访问父类的方法和成员变量。
用途
super 主要有以下几种用途:
立即学习“Java免费学习笔记(深入)”;
示例
以下示例展示了 super 的使用方法:
<code class="java">class Parent {
public Parent() {
System.out.println("Parent constructor");
}
public void print() {
System.out.println("Parent method");
}
}
class Child extends Parent {
public Child() {
super(); // 调用父类构造函数
System.out.println("Child constructor");
}
@Override
public void print() {
super.print(); // 访问父类方法
System.out.println("Child method");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.print(); // 输出:Parent constructor, Child constructor, Parent method, Child method
}
}</code>注意事项
以上就是java中super指的是什么的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号