A comprehensive analysis of construction methods and methods in Java

Source: Internet
Author: User

Differences in construction methods and methods:

The constructor method is to be the same as the class name, with no return type, called when the class is initialized.
The method is best unlike the class name, where the object is called and the static method can use the class name. Method ().

Constructors and methods differ in the following three ways: modifiers, return values, naming.

       1. As with methods, constructors can have any access to adornments:  public, Protected, private, or no adornments (usually called by package  and  friendly) .  different from the method, Constructors cannot have the following non-accessible adornments:  abstract, Final, native, static, , or  synchronized.  
        2. The return type is also very important. Method can return any type of value or no return value (void), the constructor has no return value, and no void is required.  
        3. The name of both. The constructor uses the same name as the class, and the method is different. By custom, methods usually start with lowercase letters, and constructors usually start with uppercase letters. A constructor is usually a noun because it is the same as the class name, and the method is usually closer to the verb because it shows an action.

     constructor methods and methods the usage difference between this and supper:  
   
     " The usage of this " 
    Constructors and methods use the keyword this for a very large difference. The method references this to an instance of the class that is executing the method. Static methods cannot use the This keyword, because static methods do not belong to the real   example of a class, so this does not have anything to point to. The constructor's this points to another constructor in the same class, with different argument lists, let's take a look at the following code:

Package Com.dr.gouzao;public class Platypus {    String name;    Platypus (String input) {        name = input;    }    Platypus () {This        ("John/mary Doe");    }    public static void Main (String args[]) {        platypus P1 = new Platypus ("Digger");        Platypus P2 = new Platypus ();        System.out.println (p1.name + "----" + P2.name);}    }

In the above code, there are 2 constructors with different parameter lists. The first constructor, which gives the member of the class name assignment, the second constructor, invokes the first constructor, giving the member variable name an initial value of "John/mary Doe".

In the constructor, if you want to use the keyword this, then it must be placed in the first row, and if not, it will result in a compilation error.
You can call only one of the other construction methods in a constructor, and the statement that calls the constructor method must be the first statement.


The use of "super"

Constructors and methods use the keyword super to point to a superclass, but in a different way. Method uses this keyword to execute methods in the overloaded superclass. Look at the following example:

Package com.dr.gouzao;class mammal {    void Getbirthinfo () {        System.out.println ("Born alive.");    } Class Platypus1 extends mammal {    void Getbirthinfo () {        System.out.println ("Hatch from Eggs");        System.out.print ("A mammal normally is");        Super.getbirthinfo ();    }    }

In the example above, use Super.getbirthinfo () to call the overloaded method in the superclass mammal.


The constructor uses super to call the constructor in the superclass. And this line of code must be placed on the first line, or the compilation will fail. Look at the following example:

public class Superclassdemo {    Superclassdemo () {    }}class-extends Superclassdemo {child    () {        Super ();    }}

In the above-mentioned example, the constructor child () contains super, which is to instantiate the constructor Superclassdemo in the superclass and add it to the child class.

The compiler automatically joins the code, and when we write a class without a constructor, the compiler automatically adds a constructor with no arguments.

Here are some examples of how to use the construction method:
The inheritance mechanism of a class enables subclasses to use the functionality of the parent class (that is, code), and the subclass also has the type of the parent class. The Following is a question of the order in which classes are initialized on an inheritance relationship.
Example 1:

Output Result: Superclass constructor
Subclass Constructor
Only one subclass object has been instantiated in the subclass. From the output, the program does not run its own construction method at the outset, but rather runs the default constructor of its parent class first. Note: The program automatically calls the default construction method of its parent class.
Example 2

  

Compiling this program under the JDK does not succeed. As stated in the previous example: The program initializes the subclass to find the default constructor of its parent class, the result is not found, then the compilation will not pass.

There are two ways to solve this problem:

1. Adds a default constructor method to the parent class.
2. Add a statement to the constructor of the subclass: Super (STR); and must be in the first sentence.

Both of these methods allow the program to compile, but the results are different for this program.

The result of the 1th method is:

Sub with a string.

The result of the 2nd method is:

Super with a string.
Sub with a string.

The 2nd workaround is actually to specify that the compiler does not look for the default constructor of the parent class, but rather to look for a constructor that takes a string as a parameter.

The following describes the initialization order of objects.

Example 3:

Output Result:
Test main () Start ...
One-1
One-2
One-3
Both
An object in the main () method that instantiates a class of one or both. However, when the program initializes the object of the class of both classes, it does not first invoke the constructor of the class of both, but instead initializes the member variables of the first class. Here the two classes have 3 member variables, all of which are objects of the one class, so you first call the corresponding construction method of the one class 3 times. Finally, the object that initializes the class of both.
That is, when you create an object, all the data members of the class that the object is in are initialized first, and if the member variables have objects, they also perform the initialization work in order. After all class member initialization is complete, the object is created by invoking the constructor of the class where the object is located. The constructor method is the initialization of the function.



Example 4:

Output Result:
Test main () Start ...
One-3
One-1
One-2
Two-1
------------
One-1
One-2
Two-2
If there is a static object in a class, it is initialized before the non-static object, but only once. Non-static objects are initialized each time they are called.
Example 5

Output Result:
One-3
One-1
One-2
Two-3
Test main () Start ...
One-1
One-2
Two-1
------------
One-1
One-2
Two-2
The static variables of the main class in the program are initialized before the main () method executes. Only one one-3 is output in the result, which means that if there is a static object in a class, it is initialized before the non-static object, but only once. Non-static objects are initialized each time they are called.

Example 6

Class One {one (String str) {System.out.println (str)}} Class II {static int i = 0; One one_1 = new One ("one-1"); Static one one_2 = new One ("one-2"); Static one one_3 = new One ("one-3"); Both (String str) {System.out.println (str);}} public class Test {public static void main (string[] args) {System.out.println ("Test main () Start"); System.out.println ("two.i ="  

Output Result:
Test main () Start ...
One-2
One-3
TWO.I = 0
When you create an object for the 1th time, all of the static variables in the class are initialized, and the static variables in the class are accessed for the 1th time (no objects are created), and all the static variables in the class are initialized in the order in which they are arranged in the class.

The order of initialization includes the order in which the method calls are constructed:

1. The static members of the main class are initialized first.
2. The construction method of the superclass of the main class is called from highest to lowest order.
3. Initializes the non-static object (variable) of the main class.
4. Invokes the construction method of the main class.

A comprehensive analysis of construction methods and methods in Java

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.