2024-12-14 08:00:05

Java中的super()

super()用于调用父构造函数吗? 请解释super()。


当前回答

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.

Java超级关键字的使用

Super可用于引用直接父类实例变量。 Super可用于调用直接父类方法。 Super()可用于调用直接父类构造函数。

其他回答

还有其他一些用途。

引用继承接口的默认方法:

import java.util.Collection;
import java.util.stream.Stream;

public interface SkipFirstCollection<E> extends Collection<E> {

    @Override
    default Stream<E> stream() {
        return Collection.super.stream().skip(1);
    }
}

还有一种很少使用的情况,在实例化静态子类时,使用限定的超类为超类构造函数提供一个外部实例:

public class OuterInstance {

    public static class ClassA {

        final String name;

        public ClassA(String name) {
            this.name = name;
        }

        public class ClassB {
            public String getAName() {
                return ClassA.this.name;
            }
        }
    }

    public static class ClassC extends ClassA.ClassB {
        public ClassC(ClassA a) {
            a.super();
        }
    }

    public static void main(String[] args) {
        final ClassA a = new ClassA("jeff");
        final ClassC c = new ClassC(a);
        System.out.println(c.getAName());
    }
}

然后:

$ javac OuterInstance.java && java OuterInstance
jeff

Super()不带参数地调用父构造函数。

它也可以与参数一起使用。例如super(argument1),它将调用接受一个argument1类型形参的构造函数(如果存在的话)。

它还可以用于从父类调用方法。即super.aMethod ()

更多信息和教程在这里

我已经看到了所有的答案。但大家都忘了提一个非常重要的问题:

Super()应该在构造函数的第一行中调用或使用。

这是正确的。Super用于调用父构造函数。假设你有这样一个代码块

class A{
    int n;
    public A(int x){
        n = x;
    }
}

class B extends A{
    int m;
    public B(int x, int y){
        super(x);
        m = y;
    }
}

然后你可以给成员变量n赋一个值。

super关键字可用于调用超类构造函数和引用超类的成员

当您使用正确的参数调用super()时,实际上调用了构造函数Box,它通过使用相应参数的值来初始化变量width、height和depth。你只剩下初始化它的增值权重。如果有必要,现在可以将类变量Box设为私有。放在Box类私有修饰符的字段中,并确保您可以毫无问题地访问它们。

在超类中可以有多个重载版本的构造函数,因此可以使用不同的参数调用方法super()。程序将执行与指定参数匹配的构造函数。

public class Box {

    int width;
    int height;
    int depth;

    Box(int w, int h, int d) {
        width = w;
        height = h;
        depth = d;
    }

    public static void main(String[] args){
        HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
    }

}

class HeavyBox extends Box {

    int weight;

    HeavyBox(int w, int h, int d, int m) {

        //call the superclass constructor
        super(w, h, d);
        weight = m;
    }

}