Questions about initialization in Java

Source: Internet
Author: User

Within the class, the order in which the variables are defined determines the order of initialization, and the immediate variable definitions are scattered outside the method definition, and they are still initialized before any method (including the constructor) is called.

The order in which initialization is static, followed by non-static objects

For example:

Class cat{    Private Dog Dog1=new dog (1);    Static Private Dog Dog2=new dog (2);    public cat (int n) {        System.out.println ("+n+", "Cat Only");}    } Class dog{public    Dog (int n) {        System.out.println ("Dog (" +n+ ")");}    } public class Teststatic {public    static void Main (string[] args) {        System.out.println ("Test ...");        Cat cat=new Cat (1);}    }

Operation Result:

Test ... Dog (2) Dog (1) 1th cat

  

The Cat class and the Dog class constructor print information in order to see the initialization information

In the main method, a cat class was created, with the exception of the construction method, there are two objects, one is static dog and the other is dog, because the static object is initialized first, so the Dog (2) is printed first, then the Dog (1)

Finally, we call cat's construction method, print out cat (1)

Non-static instance initialization

The contents of the initialization in {} are executed before the constructor, and each generation of the class {} will be re-initialized

Questions about initialization 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.