super() in Java

前端 未结 15 2039
逝去的感伤
逝去的感伤 2020-11-22 05:36

Is super() used to call the parent constructor? Please explain super().

相关标签:
15条回答
  • 2020-11-22 06:05

    Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.

    class Explicit() {
        Explicit() {
            super();
        }
    }
    
    class Implicit {
        Implicit() {
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:09

    Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.

    public class Alien{
       public Alien(){ //Default constructor is written out by user
       /** Implementation not shown…**/
       }
    }
    
    public class WeirdAlien extends Alien{
       public WeirdAlien(){
       super(); //calls the default constructor in Alien.
       }
    
    }
    
    0 讨论(0)
  • 2020-11-22 06:12

    For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

    public class DeveloperSteps extends ScenarioSteps {
    
    public DeveloperSteps(Pages pages) {
        super(pages);
    }........
    
    0 讨论(0)
提交回复
热议问题