Default constructors and inheritance in Java

旧时模样 提交于 2019-11-26 12:15:30

问题


I have a question about default constructors and inheritance in Java.

Generally, if you write a class and do not include any constructor, Java provides automatically for you a default constructor (one without parameters), which initializes all instance variables of the class (if there are any) with some default values (0, null, or false). If you write a constructor, however, with some parameters, and you don\'t write any default constructor, then Java does not provide a default constructor. My question is: what is the case with classes, which inherit from other classes - if I write a constructor with some parameters in them, but don\'t include a default constructor, do they inherit the default constructor of the super class?


回答1:


  1. If you do not make a constructor, the default empty constructor is automatically created.

  2. If any constructor does not explicitly call a super or this constructor as its first statement, a call to super() is automatically added.

Always.




回答2:


Constructors are not inherited.

Also, the initialization of fields is done by the virtual machine, not the default constructor. The default constructor just invokes the default constructor of the superclass, and the default constructor of Object is empty. The good point of this design is that there is no way to ever access uninitialized fields.




回答3:


Unless you use super(...) a constructor calls the empty constructor of its parent. Note: It does this on all you classes, even the ones which extend Object.

This is not inheriting, the subclasses don't get the same constructors with the same arguments. However, you can add constructors which call one of the constructors of the super class.




回答4:


The basic rule is a call (or invocation) to a constructor should be the first statement that JVM needs to execute,

So when you have a super class with only parameterized constructor and no default constructor, and base class has no explicit call to the parameterized constructor of the super class, JVM provides the super(); call which throws error as there is no default constructor for the super class, so either we provide a default constructor in the super class or we explicitly call the parameterized constructor of the super class in the base class constructor. when we give the explicit call, then JVM doesn't bother to put the line super(); as constructor invocation should be the first statement of the method, which cannot happen (because of our explicit call).




回答5:


Section 8.8.9 of the Java Language Specification explains in details what is going on:

If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

  • The default constructor has the same accessibility as the class (§6.6).
  • The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
  • The default constructor has no throws clauses.
  • If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

You can see that there is no inheritance going on here: all there is to it is the "compiler magic" with implicitly declared default constructor. The specification also makes it clear that the default constructor is added only when the class has no constructors at all, meaning that the answer to your question is "no": once you give a class a constructor, the access to the default constructor of its superclass is lost.




回答6:


If you provide a constructor then Java will not generate you a default empty constructor. So your derived class will only be able to call your constructor.

The default constructor doesn't initialize your private variables to default values. The proof is that it's possible to write a class that doesn't have a default constructor and has its private members initialized to default values. Here's an example:

public class Test {

    public String s;
    public int i;

    public Test(String s, int i) {
        this.s = s;
        this.i = i;
    }

    public Test(boolean b) {
        // Empty on purpose!
    }

    public String toString() {
        return "Test (s = " + this.s + ", i = " +  this.i + ")";
    }

    public static void main (String [] args) {
        Test test_empty = new Test(true);
        Test test_full = new Test("string", 42);
        System.out.println("Test empty:" + test_empty);
        System.out.println("Test full:"  + test_full);
    }
}



回答7:


Thumb Rule is that Sub Class should call any constructor from the base class. so if you don't have the default const the call the existing one from sub class. other wise implement the empty const in the base class to avoid the compilation problem




回答8:


The answer to your question is very simple. Implicitly(Invisible), the first statement in any constructor is 'super();' i.e. the call to super class's no parameter constructor, until you change it explicitly to something like 'this();','this(int)','this(String)','super(int)','super(String)' etc. 'this();' is current class's constructor.




回答9:


When we don't create a constructor Java creates a default constructor automatically. But when we create one or more custom constructors with arguments, Java doesn't create any default constructors. If we create one or more constructors and we want to create an object without any constructor arguments, we have to declare a empty constructor.




回答10:


There will be compile time error...because Compiler looks for default Constructor he Superclass and if its not there...its an error...and program will not Compile...




回答11:


Any constructor in subclass will call the no argument contructor(or default constructor) of parent class. if you define a parameterized constructor in parent class then you have to explicitly call the parent class constructor with super keyword else it will give the compilation error.

class Alpha 
{ 
    Alpha(int s, int p) 
    { 
        System.out.println("base");
    }

} 

public class SubAlpha extends Alpha 
{ 
    SubAlpha() 
    { 
        System.out.println("derived"); 
    } 
    public static void main(String[] args) 
    { 
        new SubAlpha(); 
    } 
}

The above code will give the compilation error:

prog.java:13: error: constructor Alpha in class Alpha cannot be applied to given types;
    { 
    ^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

The above error occurred because neither we have any no argument constructor/default constructor in parent class nor we are calling the parameterized constructor from sub class.

Now to solve this either call the parameterized constructor like this:

class Alpha 
{ 
    Alpha(int s, int p) 
    { 
        System.out.println("base");
    }

} 

public class SubAlpha extends Alpha 
{ 
    SubAlpha() 
    { 
        super(4, 5); // calling the parameterized constructor of parent class
        System.out.println("derived"); 
    } 
    public static void main(String[] args) 
    { 
        new SubAlpha(); 
    } 
}

Output

base
derived

or

define a no argument constructor in parent class like this:

class Alpha 
{ 
    Alpha(){

    }
    Alpha(int s, int p) 
    { 
        System.out.println("base");
    }

} 

public class SubAlpha extends Alpha 
{ 
    SubAlpha() 
    { 
        System.out.println("derived"); 
    } 
    public static void main(String[] args) 
    { 
        new SubAlpha(); 
    } 
}

output

derived 


来源:https://stackoverflow.com/questions/525548/default-constructors-and-inheritance-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!