Friday, March 9, 2012

Public methods and package private classes

Given these two classes
class abstract AbstractClass {
   public void doSomething() {
    System.out.println("Hello world");
   }
}

public class ConcreteClass extends AbstractClass {
}

both in package org.mydomain. What will happen if I create a new instance of ConcreteClass in another package and try to invoke doSomething()? Will that work?

The answer to this question is it depends on the JDK. 


The Sun JDK allows you to access a public method in a package private class. However, OpenJDK will throw

java.lang.IllegalAccessException: Class MyClass can not access a member of class ConcreteClass with modifiers "public"

I'm not sure what the JDK specification says about this, but the moral is
Do not have public methods in package private classes.

1 comment: