简体   繁体   中英

In java can super() be used to call any parent method or just the parent constructor

是否可以使用子类方法中的super()调用任何父类方法,或者仅用于调用父构造函数

For calling methods the syntax is super.methodName() . Just super() will call the constructor.

It's very similar to this keyword but for parent.

this() calls this classes constructor from another constructor. super() calls the parents constructor from childs constructor.

this.methodName() calls the method of the current class, super.methodName() calls the method of parent class.

EDIT: As @harry has mentioned in the comment, the parent's method should be visible to the child to actually be able to use super.methodName() . Private methods in the parent cannot be accessed.

Usage of Super keyword:

  1. super()-only the super as a constructor call will call the super class default constructor
  2. super(parameters)- calls only the parameterised constructors of its parent class.
  3. super.methodName() - calls the method of its parent class chain provided the method visibility is either public or protected.
  4. If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining , and you need to be aware of it when there is a long line of class descent

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM