Why can't there be static variables in the Java non-static inner class and can have constants?

Source: Internet
Author: User
Tags static class

Such as:
public class innerclassdemo{
int x;
Class a{
static int a = 0;//is not legal to write this way.
static final int b=0;//It's legal to write this.
}
}
Answer: to put it simply, define a static domain or method that requires a static environment or a top-level environment, where the static environment specifically says that if you add static Class A In your example, you're OK.
A non-static inner class is dependent on an outer class object, and the static domain/method is not dependent on the object-it is only related to the class, so a static domain/method cannot be defined in a non-static inner class and cannot be compiled.
Constants are available (whether or not static) because Java determines all constants at compile time and puts them into so-called constant pools. The mechanism of constants is different from normal variables.

To go into the Java class load order, load the class first, execute the static variable initialization, and then execute the creation of the object, if we are going to execute the variable int a initialization in the code, you must first execute the load external class, then load the inner class, and finally initialize the static variable A, The problem is that in loading the inner class, we can think of the inner class as a non- static member of the outer class, whose initialization must be done after the outer class object is created, and the inner class must be completed after the instantiation of the instance. The Java virtual machine requires that all static variables be completed before the object is created, thus creating a contradiction.
And the Java constant in the memory of the constant pool, its mechanism and variables are different, at compile time, load constants do not need to load the class, so there is no such contradiction.

Why can't there be static variables in the Java non-static inner class and can have constants?

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.