我正在处理一个继承了 JFrame
的类。
这不是我的代码,它在开始构建GUI之前调用了 super
。我想知道为什么要这样做,因为我通常只需访问超类的方法而无需调用 super();
。
我正在处理一个继承了 JFrame
的类。
这不是我的代码,它在开始构建GUI之前调用了 super
。我想知道为什么要这样做,因为我通常只需访问超类的方法而无需调用 super();
。
super()
,因此通常不需要显式调用它。但是,如果父类的构造函数需要参数,并且您希望指定它们,则可以使用带参数的super()
调用。此外,在父类的构造函数需要参数且没有默认的无参构造函数的情况下,您需要使用带参数的super()
调用。super()
进行显式调用可使您更好地控制框架的标题:class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
super()
会自动进行,这就是为什么你在代码中从未必须执行它的原因。它已经为你执行了。super
。编译器将确保你正确地实例化该类。因此这不是你必须过分担心的事情。super()
,都不会影响你调用父类方法的能力。 class parent {
String str="I am parent";
//method of parent Class
public void foo() {
System.out.println("Hello World " + str);
}
}
class child extends parent {
String str="I am child";
// different foo implementation in child Class
public void foo() {
System.out.println("Hello World "+str);
}
// calling the foo method of parent class
public void parentClassFoo(){
super.foo();
}
// changing the value of str in parent class and calling the foo method of parent class
public void parentClassFooStr(){
super.str="parent string changed";
super.foo();
}
}
public class Main{
public static void main(String args[]) {
child obj = new child();
obj.foo();
obj.parentClassFoo();
obj.parentClassFooStr();
}
}
它只是调用了超类的默认构造函数。
我们可以使用super关键字访问超类成员
如果您的方法覆盖了其超类的某个方法,则可以通过使用关键字super
调用被覆盖的方法。您还可以使用super引用隐藏字段(尽管不建议隐藏字段)。考虑这个类,Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
// 这里有一个子类,叫做Subclass,它重写了printMethod()
方法:
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
在子类中,简单名称 printMethod()
指的是在子类中声明的方法,它覆盖了超类中的同名方法。因此,为了引用从超类继承的 printMethod()
方法,子类必须使用限定名称,就像使用 super 一样。编译和执行子类会打印以下内容:
Printed in Superclass.
Printed in Subclass
JFrame
可能不是您想要做的事情。扩展意味着 is-a 关系。除非您正在创建新的窗口组件,否则您应该扩展JComponent
。 - Jeffrey