Chapter 1 class and object knowledge points in the second quarter of Java, and section 2 of java

Source: Internet
Author: User

Chapter 1 class and object knowledge points in the second quarter of Java, and section 2 of java

 

JavaStatic Method in

1,Static members of the same type can be called directly in static methods, but non-static members cannot be called directly.For example:

 

 

To call non-static variables in a static method, you can create a Class Object and access non-static variables through the object.. For example:

 

2,In common member methods, you can directly access non-static and static variables of the same type., As shown below:

 

 

3, Non-static methods cannot be called directly in static methods. You must use objects to access non-static methods.For example:

 

 

 

 

Static initialization block in Java

In Java, values can be assigned through initialization blocks. For example:

 

 

The class declaration can contain multiple initialization blocks. When a class instance is created, these code blocks are executed in sequence. Static initialization blocks are called static initialization blocks.

Note:Static initialization blocks are executed only when the class is loaded and only once. At the same time, static initialization blocks can only assign values to static variables and Cannot initialize common member variables..

Let's look at a piece of code:

 

 

Running result:

 

 

The output result shows that the static initialization block is executed first when the program is running, then the common initialization block is executed, and the constructor is executed finally. Because the static initialization block is only executed once during class loading, the static initialization block is not executed when the object hello2 is created again.

 

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.