Search code examples
javastatic-classes

Accessing static classes in another java file


Is it possible that I can access a static class in another *.java file?

My scenario is that I have two java files in the same folder, A.java and B.java:
In A.java, which does not only include class A but static class C:

public class A {
    public static void main(String[] args) {
          //code  
    }
    static class C{
        //code
    }
}

In B.java, which will use methods of class C:

public class B {    
     //code, use C's methods  
}

In the file B.java, I want to use class C's methods declared in the A.java; however, the compiler does not recognize the class C, even though I put the A.java and B.java in the same folder. I suppose I do not need to import anything because both java files are in the same folder, doesn't it? Does anyone know how to solve this problem? Thank you!


Solution

  • Please note that class C has no access modifier and will only be visible in the same package. To clarify: A subclass won't inherit access modifiers from its encapsulating class.

    If A and B are on the same packages you can access C from B by using A.C.<code> If you would like to make C available to classes outside of A's package you need to make the subclass C public:

    // [...]
    // insead of >>static class C {<<
    public static class C {
    // [...]
    

    After you've changed the access modifier you can use C as mentioned above (A.C.<code>)