0

I have file structure and code like this:

../inside/A.java

package inside;
public class A{protected static void someStaticMethod(){}}

../inside/B.java

package inside;
import inside.A;
public class B extends A{protected static void someStaticMethod(){}}

../inside/C.java

package inside;
import inside.B;
public class C extends B{protected static void someStaticMethod(){}}

../Z.java

import inside.*;
class Z extends B{
  public static void main(String args[]){
  A.someStaticMethod();
  B.someStaticMethod();
  C.someStaticMethod(); // Fine at compile-time but IllegalAccessError at run-time.
}

}

At line with comment there is no error at compile-time but at runtime there is IllegalAccesError.

What is the true reason for this behavior?

I have found a question – Why does Java bind variables at compile time? – where in the first answer there is maybe mentioned the reason but I am definitely not sure it is.

Community
  • 1
  • 1
Yarl
  • 728
  • 1
  • 7
  • 26

2 Answers2

0

The error is thrown because you've set the visibility of the methods to protected, this means the methods can only be accessed from a sub class or in the same package.

So the reason why the IllegalAccessError is thrown is because your class Z isn't a sub class from C nor is Z in the same package as C.

Eclipse gives me a complier error:

"Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method doSomething() from the type C is not visible"

Dimitrios Begnis
  • 823
  • 6
  • 16
  • I know what is the reason for this error but I want to know **why the error is not found and compile-time** (unless I am using javac from cmd to compile Z.java). – Yarl Apr 17 '16 at 13:38
  • 1
    oh sorry, I missunderstood your question. Then I can't help you. As shown in my answer eclipse gives me a complie time error with exact the same code so I don't know why it isn't working for you. – Dimitrios Begnis Apr 17 '16 at 13:43
  • That quite funny because in NetBeans there is no error till run-time. – Yarl Apr 17 '16 at 14:42
  • @Dimitros Begnis Can you please removal you answer so this unhelpful question can be removed? – Yarl Jun 11 '20 at 12:21
0

It is probably bug in javac – see http://www.coderanch.com/t/664583/java/java/Static-methods-inheritance-java-lang.

Yarl
  • 728
  • 1
  • 7
  • 26