Two points should be known when calling constructor to create an object

zhaozj2021-02-12  169

I. When you have a parent class, when you create your own object, first call the parent class constructor, there are two cases:

1. When the parent class does not have a constructor (ie, only the default implicit-free-free constructor), first call the implicit constructor, then call its own constructor;

Public class test () {public test () {} public test (int i) {system.out.println (i); public static void main (string args []) {test t = new test (1);} } Class Sup {}

Note: Either parent class has no explicit constructor, or the parent class must declare an explicit-free constructor, both of them! The parent class has other constructors - there is a refinement, but there is no construct The compile period error occurs when a compile period occurs.

2. When the parent class has an explicit constructor - indicates that the non-array constructor is stated, the no-argument is first modulated, and then the constructor is called.

Public class test extends sup {

Public test () {

}

Public Test (INT I) {

System.out.println (i);

}

Public static void main (string args []) {

Test T = New Test (1);

}

}

Class sup {

Public SUP () {// --------- Call the constructor

System.out.println (3);

}

Public SUP (INT I) {

System.out.println (4);

}

}

Second, the class with no parent class is to call your own constructor when you create your own object, and you don't have to call your own no-argument.

Public class test {

Public Test (INT I) {

System.out.println (i);

}

Public static void main (string args []) {

Test T = New Test (1);

}

}

转载请注明原文地址:https://www.9cbs.com/read-6168.html

New Post(0)