super只能用在构造方法里面吗?
super关键字并不仅限于在构造方法中使用。在Java中,super关键字有两个主要的用途:
-
在子类的构造方法中调用父类的构造方法。这是
super的一个常见用法,通常是在子类的构造方法的第一行使用,用于显式地调用父类的构造方法。例如:
public class Child extends Parent { public Child() { super(); // Call the constructor of Parent class // ... } } -
在子类的方法中调用父类的方法。这包括在子类中被重写的方法和父类中其他的方法。使用
super关键字可以让你在子类的方法中调用父类的同名方法。例如:
public class Child extends Parent { @Override public void someMethod() { super.someMethod(); // Call the version of someMethod() in Parent class // ... } }
在上面的代码中,Child类重写了Parent类的someMethod()方法,但在Child类的someMethod()方法中,我们使用super.someMethod()来调用Parent类中的someMethod()方法。
所以,super关键字可以在子类的任何方法中使用,不仅限于构造方法。
本文来自博客园,作者:news_one,转载请注明原文链接:https://www.cnblogs.com/new-one/p/17832437.html

浙公网安备 33010602011771号