Java Construction methods

Source: Internet
Author: User
Tags instance method

Overloaded construction method, default constructor method, subclass call constructor method of parent class, scope of construction method, access level of construction method

In most cases, the final step of initializing an object is to invoke the constructor of the object. The construction method is responsible for initializing the object, assigning the appropriate initial value to the instance variable. The constructor method must satisfy the following syntax rules:

(1) The method name must be the same as the class name.

(2) Do not declare the return type.

(3) cannot be modified by static, final, synchronized, abstract and native. The construction method cannot inherit from the quilt class, so use final and

The abstract modification has no meaning. The constructor method is used to initialize a newly created object, so there is no point in using static modifiers. Multiple threads do not create the same object with the same memory address at the same time, so it is not necessary to decorate with synchronized. In addition, the Java language does not support the construction of native types.

In the following sample class, the sample (int x) method with an int return type is just a normal instance method and cannot be constructed as a method:

public class Sample {

private int x;

Public Sample () {//Non-parametric construction method

This (1);

}

public Sample (int x) {//With parameter construction method

This.x=x;

}

public int Sample (int x) {//Not construction method

return x + +;

}

}

Although the above example can be compiled through, but the instance method and construction method with the same name, not good programming habits, easy to cause confusion. For example, the Mystery () method of the following mystery class has a void return type and is therefore a normal instance method:

public class Mystery {

Private String S;

public void Mystery () {//Is not a constructor method

s = "constructor";

}

void Go () {

System.out.println (s);

}

public static void Main (string[] args) {

Mystery m = new Mystery ();

M.go ();

}

}

The printed result of the above program is null. Because the mystery instance is created with the new statement, the default constructor method for the mystery class is called instead of the Mystery () method with the void return type above.

Overloaded Construction methods

When an object is created by using the new statement, the object may have different initialization behavior under different conditions. For example, for a new employee in the company, at the outset, it is possible that his name and age are unknown, and it may be that only his name is known, and the name and age are known. If the name is unknown, set the name as "anonymous" and, if the age is unknown, set the age to 1.

Multiple initialization behavior of an object can be expressed by overloading the construction method. The employee class of the following routines is constructed in three overloaded forms. In multiple construction methods of a class, there may be some duplication. To improve the reusability of code, the Java language allows the use of this statement to invoke another constructor method in a constructor.

Routine Employee.java

public class Employee {

private String name;

private int age;

/** Call this construction method when the employee's name and age are known */

Public Employee (String name, int age) {

THIS.name = name;

This.age=age;

}

/** Call this construction method when the employee's name is known and the age is unknown */

Public Employee (String name) {

This (name,-1);

}

/** Call this construction method when the employee's name and age are unknown */

Public Employee () {

This ("Anonymous");

}

public void SetName (String name) {this.name=name;}

Public String GetName () {return name;}

public void Setage (int.) {this.age=age;}

public int getage () {return age;}

}

The following program creates three employee objects, respectively, by three construction methods:

Employee Zhangsan=new employee ("Zhang San", 25);

Employee Lisi=new Employee ("John Doe");

Employee Someone=new employee ();

In the employee (string name) construction method, the This (NAME,-1) statement is used to invoke the employee (string Name,int Age) Construction method. In the employee () construction method, the This ("anonymous") statement is used to invoke the employee (String name) construction method.

When you use the this statement to invoke other construction methods, you must adhere to the following syntax rules:

(1) If the This statement is used in a constructor method, it must be the first statement of the construction method (regardless of the comment statement).

The following construction methods are illegal:

Public Employee () {

String name= "Anonymous";

This (name); Compile error, this statement must be the first statement

}

(2) The This statement can be used only in one constructor method to invoke the other constructor methods of the class, rather than using the this statement in an instance method to invoke the other constructor methods of the class.

(3) Other construction methods can be invoked only with the this statement, and not directly by method names.

The following method of calling the constructor is illegal:

Public Employee () {

String name= "Anonymous";

Employee (name); Compile error, cannot call constructor directly by method name

}

Default constructor method

The default constructor method is a constructor that has no parameters and can be divided into two types: (1) The default constructor method that is implicitly defined by the default constructor method (2).

In the Java language, each class has at least one construction method. To ensure this, if no constructor is provided in the user-defined class, the Java language automatically provides an implicit default constructor method. The constructed method has no parameters, is decorated with public, and the method body is empty, in the following format:

Public ClassName () {}//implied default constructor method

You can also explicitly define a default construction method in your program, which can be any level of access. For example:

Protected Employee () {//Cheng default construction method defined

This ("Anonymous");

}

If one or more construction methods are explicitly defined in a class, and all of the constructor methods have parameters, the class loses its default construction method. In the following program, the Sample1 class has an implicit default constructor method, the Sample2 class has no default constructor, and the Sample3 class has an explicitly defined default constructor method:

public class sample1{}

public class sample2{

Public Sample2 (int a) {System.out.println ("My Constructor");}

}

public class sample3{

Public Sample3 () {System.out.println ("My Default Constructor");}

}

You can call the default construction method of the Sample1 class to create a Sample1 object:

Sample1 s=new Sample1 (); Legal

The Sample2 class does not have a default construction method, so the following statement causes a compilation error:

Sample2 s=new Sample2 (); Compilation error

The Sample3 class explicitly defines the default constructor method, so the following statement is legal.

Sample3 s=new Sample3 ();

Subclass calls the constructor method of the parent class

The construction method of the parent class cannot inherit from the quilt class. The following myexception classes inherit the Java.lang.Exception class:

public class MyException extends exception{}//MyException class has only one implicit default construction method

Although the following form of construction is defined in the exception class:

Public Exception (String msg)

However, the MyException class does not inherit the constructor of the above exception class, so the following code is not valid:

Compile error, MyException class does not exist such a construction method

Exception e=new myexception ("Something is Error");

In the constructor of a subclass, the constructor of the parent class can be called through the Super statement. For example:

public class MyException extends exception{

Public MyException () {

Calls the exception (String msg) Construction method of the exception parent class

Super ("Something is Error");

}

Public myexception (String msg) {

Calls the exception (String msg) Construction method of the exception parent class

Super (MSG);

}

}

When you invoke the constructor method of a parent class with a super statement, you must adhere to the following syntax rules.

(1) In the constructor method of a subclass, you cannot call the constructor of the parent class directly from the parent class method name, but instead use the Super statement.

The following code is illegal:

Public myexception (String msg) {

Exception (msg); Compile error

}

(2) When using the Super statement, it must be placed at the front.

The following code is illegal:

Public MyException () {

String msg= "Something wrong";

Super (MSG); Compilation error, the Super statement must be the first statement of the constructor method

}

When you create an object of a subclass, the Java Virtual machine first executes the constructor of the parent class, and then executes the constructor of the subclass. In the case of multi-level inheritance, the constructor of each class is executed from the topmost parent of the inheritance tree, which guarantees that the instance variables inherited from all direct or indirect parent classes are properly initialized by the child class object. For example, the following base parent and sub subclasses have one instance variable A and B, and when you construct a sub instance, the two instance variables will be initialized.

public class base{

private int A;

Public Base (int a) {this.a=a;}

public int Geta () {return A;}

}

public class Sub extends base{

private int B;

Public Base (int a,int b) {super (a); this.b=b;}

public int Getb () {return B;}

public static void Main (String args[]) {

Sub Sub=new Sub (up);

System.out.println ("a=" +sub.geta () + "b=" +sub.getb ()); Print A=1 b=2

}

}

In the following routines (Son.java), the Son class inherits the Father class, and the Father class inherits the Grandpa class. These three classes explicitly define the default construction method, and a constructor with parameters is defined.

Routine Son.java

Class grandpa{

Protected Grandpa () {

System.out.println ("Default Grandpa");

}

Public Grandpa (String name) {

SYSTEM.OUT.PRINTLN (name);

}

}

Class Father extends grandpa{

Protected Father () {

SYSTEM.OUT.PRINTLN ("Default Father");

}

Public Father (String grandpaname,string fathername) {

Super (Grandpaname);

System.out.println (Fathername);

}

}

public class Son extends father{

Public Son () {

SYSTEM.OUT.PRINTLN ("Default Son");

}

Public Son (String grandpaname,string fathername,string sonname) {

Super (Grandpaname,fathername);

System.out.println (Sonname);

}

public static void Main (String args[]) {

Son s1= new son ("My Grandpa", "My Father", "my Son"); ①

Son s2=new son (); Ii

}

}

Execute the ① clause of the main () method above and print the result as follows:

My Grandpa

My Father

My Son

When the subclass's construction method does not explicitly invoke the constructor of the parent class with the Super statement, the Java virtual opportunity automatically calls the parent class's default construction method when the subclass object is created by this constructor method. Execute the ② clause of the main () method of the son class above, and print the result as follows:

Default Grandpa

Default Father

Default Son

A compilation error occurs when the subclass's construction method does not explicitly call the parent class's construction method with a super statement, and the parent class does not provide a default constructor method. For example, to make appropriate modifications to the routine Son.java, remove the default constructor method explicitly defined in the Grandpa class:

Protected Grandpa () {

System.out.println ("Default Grandpa");

// }

In this way, the Grandpa class loses its default constructor, and when the default constructor method for the Father class is compiled, the compilation error occurs because the default constructor method for the Grandpa class is not found. If you change the protected access level of the default constructor method of the Grandpa class to private access level, you will also cause compilation errors because the default constructor of the Father class cannot access the private default constructor of the Grandpa class.

In the following example, the default constructor method of a subclass sub does not invoke the constructor of the parent class through the Super statement, but instead calls the other construction method sub (int i) through the this statement, and the base of the parent class base is called in sub (int i) through the Super statement ( int i) constructs the method. Thus, the base (int i) construction method of the parent class base is called first, regardless of which constructor of the sub class is used to create the sub instance.

Class base{

Base (int i) {System.out.println ("Call Base (int i)");}

}

public class Sub extends base{

Sub () {this (0); System.out.println ("Call Sub ()");}

Sub (int i) {super (i); System.out.println ("Call Sub (int i)");}

public static void Main (String args[]) {

Sub Sub=new Sub ();

}

}

Executes the new sub () Statement of the main () method of the Sub class above, printing the result as follows:

Call Base (int i)

Call Sub (int i)

Call Sub ()

In the following example, there is no constructor defined in the base class, and it actually has an implicit default constructor method:

Base () {}

The Sub (int i) Construction method of the Sub class does not explicitly invoke the constructor of the parent class with the Super statement, so when the sub instance is created, the implicit default constructor of the base parent class is called first.

Class base{}//has an implied default construction method

public class Sub extends base{

Sub (int i) {System.out.println (i);}

public static void Main (String args[]) {

System.out.println (New Sub (1)); Printing 1

}

}

Scope of the construction method

The constructor method can only be called in the following ways:

(1) Other constructor methods of the current class call it through the this statement.

(2) The construction method of the subclass of the current class is called by the Super statement.

(3) Call it through the new statement in the program.

For the code of the routine (Sub.java), the reader should analyze the reason for some of the statement compilation errors themselves.

Routine Sub.java

Class base{

Public Base (int i,int j) {}

Public Base (int i) {

This (i,0); Legal

Base (i,0); Compilation error

}

}

Class Sub extends base{

Public Sub (int i,int j) {

Super (i,0); Legal

}

void method1 (int i,int j) {

This (I,J); Compilation error

Sub (I,J); Compilation error

}

void Method2 (int i,int j) {

Super (I,J); Compilation error

}

void method3 (int i,int j) {

Base S=new Base (0,0); Legal

S.base (0,0); Compilation error

}

}

Access level of the construction method

The construction method can be in one of the four access levels of public, protected, default, and private. This section highlights the significance of the construction method at the private level.

When the constructor method is private, it means that it can only be accessed in the current class: it is called through the this statement in other constructor methods of the current class, and it can also be called through the new statement in the member method of the current class.

In one of the following situations, you can declare all the constructor methods of a class as private types.

(1) This class contains only static methods that are called by other programs, and there are no instance methods. Other programs do not need to create instances of the class to access static methods of the class. For example, the Java.lang.Math class conforms to this situation, and in the Math class, a series of public static methods for mathematical operations are provided, and the only way to construct an instance of the math class for an external program is to disallow it from being created by the private type:

Private Math () {}

Classes of the abstract type are also not allowed to be instantiated. You might ask, is it possible to define the math class as an abstract type, and not to prevent the math class from being instantiated?

Public abstract class math{...}

If a class is an abstract class, it means that it is dedicated to inheriting classes, can have subclasses, and can create instances of specific subclasses. The JDK does not want the user to create a subclass of the math class, in which case it is more appropriate to define the class's construction method as a private type.

(2) Prohibit this class from being inherited. When all the constructor methods of a class are private types, if its subclasses are defined, then the constructor of the subclass cannot invoke any of the constructor methods of the parent class, and therefore causes a compilation error. Declaring a class as the final type can also prohibit the class from being inherited. The difference between the two is:

1) If a class allows another program to construct its instance with a new statement, but does not allow the owning of subclasses, declare the class as the final type.

2) If a class does not allow other programs to construct its instance with the new statement, and it does not allow the owning of subclasses, declare all the constructor methods of the class as private types.

Because most classes allow other programs to construct instances of it with new statements, it is more common to prohibit classes from being inherited with the final modifier.

(3) This class needs to encapsulate the details of constructing its own instance, not allowing other programs to create instances of this class from the new statement, which provides static methods to other programs that obtain their own instances, called Static factory methods.

Java Construction methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.