Workarounds for "No enclosing instance of type * is accessible" in Java

Source: Internet
Author: User

This typically occurs when you "use internal classes in static methods"

Test code:

public class Test {public static void main (string[] args) {A A = new A (1);} Class A {int x;public a () {}public A (int x) {this.x = x;}}}

The above code in the main function will have a compile error, in order to solve the problem, let us first look at the compiler prompt:

The compiler tells us that there is no instance of the test class that is accessible, which means that the instance is going to be used, and that place is used? Looking at the parentheses in the back, "x.new A ()", New A () is actually x.new a (), where X is an instance of test. So we can first create an instance of test and then use the new method of this instance to new A ().

You can then change to the following code:

public class Test {public static void main (string[] args) {test test = new test (); A = Test.new A (1);} Class A {int x;public a () {}public A (int x) {this.x = x;}}}

Understand this to explain the following code:

public class Test {public static void main (string[] args) {test test = new test (); A = Test.new A (1); b b = new B (2);//The b here is not an internal class, so there is no such problem so can be directly written newa.aa AA = a.new AA (3);} Class A {int x;public a () {}public A (int x) {this.x = x;} Class AA {int x; AA () {}aa (int x) {this.x = x;}}}} Class B {int x;public B () {}public B (int x) {this.x = x;}}

Alternatively, change the inner class to static by using an external method:

public class Test {public static void main (string[] args) {A A = new A ();} Static Class A {int x;public a () {}public A (int x) {this.x = x;}}}

  

Workarounds for "No enclosing instance of type * is accessible" 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.