Prashant Gurav
Prashant Gurav

Reputation: 503

Default access specifier in Java is accessible from outside the class

class HelloWorld {
    public static void main(String arg[]) { 
        System.out.println("Hello World!");
    }
}

Using javac HelloWorld.java and java HelloWorld, the code compiles and runs well. Since default access specifier in Java is package, how is it possible? It must have protection from outsider...

Upvotes: 0

Views: 147

Answers (2)

Gaurav Manral
Gaurav Manral

Reputation: 600

Default Access modifier means you can only access that class in that package.

what you are doing here is, running and compiling the class. This has nothing to do with modifiers and accessibility.

You will always Run & Compile classes like that.

What matters is that your class is accessible in the class or package that is being run.

You can not access a class with Default modifier in sub package or other package. A default class will only be accessible i the same package, otherwise you will get compile time error.

As far as your code is concerned you are doing nothing like that.

Suppose -

class HelloWorld {
public static void main(String arg[]) { 
    System.out.println("Hello World!");
}
}

And

Class Hello extends HelloWorld{
// some code here
}

Now if you compile class Hello, then it will give you following error.

 class, interface, or enum expected

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

Access modifier restricts access during compile time. But it is allowed to load a class with any access modifier, use reflection to find the main method and run it. This is what java tool does when lanching from a class. See http://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html

Upvotes: 1

Related Questions