只能从子类构造函数中调用 super() 吗?| 爪哇

第二位

所以我理解super()调用父类的构造函数并且我已经多次使用它。但是,我从未在子类的构造函数之外使用它。是否可以super()从子类构造函数外部调用既然super只有附加到派生类时才有意义,那么是否可以将其视为派生类的成员函数?我最初在尝试使用对象调用 super 时遇到了这个问题(只是在试验)。

有可能做这样的事情吗?

class Animal {
    Animal() {
        System.out.println("Animal's constructor was called.");
    }
}

class Puppy extends Animal {
    Puppy() {
        System.out.println("Puppy's constructor was called.");
    }
}

public class Test {
    public static void main(String[] args) {
        Puppy pupper = new Puppy();
        pupper.super();
    }
}
MC帝王

不,这是不可能的,不是在构造函数体之外。

Java语言规范§8.8.7.1说的情况如下:

ExplicitConstructorInvocation:
  [TypeArguments] this ( [ArgumentList] ) ;
  [TypeArguments] super ( [ArgumentList] ) ;
  ExpressionName . [TypeArguments] super ( [ArgumentList] ) ;
  Primary . [TypeArguments] super ( [ArgumentList] ) ;

在这里,在构造函数体(第 8.8.7 节)中,super()是允许的,但在其他地方是不允许的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

数组中的数组很奇怪吗?爪哇

编译器在调用基类构造函数之前会在子类构造函数中寻找** super **关键字吗?

在构造函数中调用this()隐式调用super()是真的吗?

URLClassLoader + loadClass +在独立进程上调用main方法吗?爪哇

在构造函数中为静态成员变量赋值会导致任何问题吗?(爪哇)

不必在构造函数中放置super()吗?

可以调用[super loadView]吗?

python中的super是多余的吗?

使用继承没有正确设计属性吗?在序列化中造成麻烦。爪哇

返回错误的值,但在系统中可以正常读取吗?爪哇

s在Java中占用3个字节吗?时间:字符串s =“ abc”; 爪哇

当前的Ruby方法是通过super调用的吗?

我可以在调用this()/ super()以及初始化任何最终字段之前在构造函数中插入指令吗?

每次扩展类并需要其构造函数来触发时,都必须调用super吗?

在子类构造函数中调用getClass()总是安全吗?

Java的:从子类中调用super.getClass()

我可以在 python 中循环调用 super 吗?

爪哇 - 的IntelliJ - JList的在JScrollPane中

从对象中获取数据; 爪哇

如果需要,super()是唯一可以隐式插入构造函数中的代码吗?

在Promise中调用super()方法:'super'关键字在这里意外吗?

构造函数中的super()

当超类只有一个带有参数的构造函数时,所有带有参数的子类的构造函数都需要super(args)吗?

__init__可以在调用super之后自动执行代码吗?

扩展View时始终需要调用super吗?

如果仅调用super .__ init__是必需的__init__吗?

在python的__str__方法上调用super()吗?

Jodatime在天和月中不使用0前缀吗?爪哇

单击JButton时JList会滚动吗?爪哇