java - Why do this() and super() have to be the first statement in a constructor? -
Java "post-text" itemprop = "text">
It is necessary for Java that if you call it (or) super () in the constructor, then this will be the first statement. Why?
For example:
public class MyClass {public MyClass (int x) {}} public class MySubClass MyClass {public MySubClass (int a, int b) extension Does {int c = a + b; Super (c); // COMPILE ERROR}}
Sun Compiler says "Super should be the first statement in the call constructor". Eclipse compiler says that "Constructor call should be the first statement in a constructor."
However, you can re-arrange the code:
public class MySubClass MyClass {public MySubClass (int a, int b) {super (a + b) Expands; // is ok}}
Here's another example:
Public class Myls {public MyClass (list list) {}} Public class MySubClassA MyClass Enhances {public MySubClassA (object items) {// Create a list that contains the item, and pass the list to Super List List = New Arrayist (); List.add (item); Super (list); // COMPILE ERROR}} Public class MySubClassB MyClass {extends public MySubClassB (object items) {// Create a list that includes items, and set the list to Super Super (Arrays.asList (new object [] { Item})); // OK}}
So, before calling it super you can not stop the argument from executing this is preventing you from executing the argument That you can not fit into a single expression
There are rules for this call ()
. The compiler says "this should be the first statement to call the constructor."
Why does the compiler do these restrictions? Can you give a code example, if the compiler did not have this restriction then what would be worse?
the original class ' constructor
to the subclasses' creator
Should be called before. This will ensure that if you call on any of the parental classes in your constructor, the parent class has already been properly set up.
The ElGS pass is completely legal to the super constructor you are trying to do, all you need to do is create those Argus Inline, as you are doing, or have them in your constructor And then send them to super
:
increases public MySubClassB MyClass {public MySubClassB (object [] myArray) {super myArray); }}
If the compiler has not implemented this, you can:
public MySubClassB MyClass {public MySubClassB (object [] myArray) {SomeMethodOnSuper (); // error super not yet made super (myArray); }}
In those cases where parent
class has a default constructor, call super to you by compiler
Is inserted from. Since every class in Java is derived from the object
, the object constructor should be called in some way and it should be executed first. The super entry of super () by the compiler allows the super to appear first, it ensures that the constructor body is executed in the correct order, which will be: object -> parent -> child -> ChildofBill -> Sounsforth