Codebender
Codebender

Reputation: 14471

Why am I not able to access static inner class through an instance

Let's say we have a class Test like this,

public class Test {

    public static void main(String... args) {
    }

    public static class InnerTest {
        public void test() {
        }
    }
}

I agree that, I should access static fields using the class name, like

Test.main();
Test.InnerTest obj = new Test.InnerTest();

But we can also access the static member's through instances,

Test test = new Test();

test.main(); // Compiler warning but WORKS fine.

// But I can't do any of this.
Test.InnerTest itest = test.new InnerTest(); // Illegal enclosing instance specification for type Test.InnerTest
Test.InnerTest itest = new test.InnerTest(); // test cannot be resolved to a type
Test.InnerTest itest = test.new Test.InnerTest(); // Cannot allocate the member type Test.InnerTest using its compound name when qualified by an enclosing instance. The member type name is resolved relatively to the qualifying instance type

I just want to learn why something like this is not possible? I am not able to completely understand from the errors reported.

Upvotes: 3

Views: 980

Answers (3)

Rafael
Rafael

Reputation: 2676

IMHO The problem is you are trying to think about it as a "calling method" way and it's nothing related with this since creating a new instance with "new" keyword is a completely different process.

The syntax for the "new" keyword is defined in the Java Languaje Specification and requires a type name following it. In the case of the static inner classes this identifier has to be constructed relative to the parent class name.

https://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

It is just Java Languaje is build to work this way.

Upvotes: 0

Nathan Hughes
Nathan Hughes

Reputation: 96385

My guess: inner classes were added later, with 1.1. By the time inner classes were being designed it was apparent allowing access to static members through the instance was a mistake. It was too late to change this for existing cases but they could avoid adding it for the new functionality.

Upvotes: 2

Casper
Casper

Reputation: 216

Test.InnerTest itest = test.new InnerTest(); - object test does not have method new

Test.InnerTest itest = new test.InnerTest(); - everything on the right side of new operator must by a Type

Test.InnerTest itest = test.new Test.InnerTest(); - combination of both remarks

What are really trying to do? Create instances of inner classes? Are you looking for a factory method?

Upvotes: 0

Related Questions