Non-static instance initialization

Source: Internet
Author: User

Java also has a similar syntax called instance initialization, which is used to initialize non-static variables for each object. For example:

: Initialization/mugs.java

Java "Instance initialization."

Class Mug {

Mug (int marker) {

System.out.println ("Mug (" + marker + ")");

}

void f (int marker) {

System.out.println ("f (" + marker + ")");

}

}

public class Mugs {

Mug Mug1;

Mug Mug2;

{

MUG1 = new Mug (1);

MUG2 = new Mug (2);

System.out.println ("Mug1 & Mug2 initialized");

}

Mugs () {

System.out.println ("Mugs ()");

}

Mugs (int i) {

System.out.println ("Mugs (int)");

}

Publis static void Main (string[] args) {

SYSTEM.OUT.PRINTLN ("Inside Main ()");

New Mugs ();

System.out.println ("New Mugs () completed");

New Mugs (1);

System.out.println ("New Mugs (1) completed");

}

}/* Output:

Mug (1)

Mug (2)

MUG1 & MUG2 Initialized

Mugs ()

New Mugs () completed

Mug (1)

Mug (2)

MUG1 & MUG2 Initialized

Mugs (int)

New Mugs (1) completed

*///:~

The instance initialization clause in this:

{

MUG1 = new Mug (1);

MUG2 = new Mug (2);

System.out.println ("Mug1 & Mug2 initialized");

}

It appears to be exactly the same as a static initialization clause, except the static keyword, which is necessary to support the initialization of an anonymous inner class, but it also allows you to guarantee that whatever display constructor is called, some operations will occur. You can see from the output that the instance initialization clause was executed before the two constructors.

  

Non-static instance initialization

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.