我正在处理扩展了JFrame
的类。
这不是我的代码,它在开始构建GUI之前先调用super
。我想知道为什么要这样做,因为我总是只访问超类的方法而不必调用super();
对于具有父级的所有类(这是Java中的每个用户定义的类),没有任何参数的隐式调用super()
,因此通常不需要显式调用它。但是,如果父级的构造函数采用参数,并且您希望指定它们,则may使用带有参数的对super()
的调用。此外,如果父级的构造函数接受参数,并且没有默认的无参数构造函数,则您将[[need调用带参数的super()
。
super()
使您对框架标题有一些额外的控制:class MyFrame extends JFrame
{
public MyFrame() {
super("My Window Title");
...
}
}
super()
的调用。这就是您无需在代码中执行此操作的原因。已为您完成。当您的超类没有no-arg构造函数时,编译器将要求您使用适当的参数调用super
。编译器将确保您正确实例化该类。因此,您不必担心太多。
无论您是否在构造函数中调用super()
,它都不会影响您调用父类的方法的能力。
作为旁注,为了清楚起见,通常最好手动进行该调用。
我们可以使用super方法访问超类元素
考虑到我们有两个类,Parent类和Child类,它们具有foo方法的不同实现。现在在子类中,如果我们要调用父类的方法foo,可以通过super.foo();来实现。我们也可以通过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引用隐藏字段(尽管不建议使用隐藏字段)。考虑这个类,超类: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