What is the default access modifier to a Java Class ?

If you don’t specify an access modifier to a Java class, as shown below, the Class becomes private to the package.

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
package com.wonder;
public class HelloWorld {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World !!");
HelloWorldBrother hwc = new HelloWorldBrother ();

}

}

class HelloWorldBrother
{
public HelloWorldBrother ()
{
System.out.println ( "Hello World’s Brother Class is called" );
}
}
[/java]

In this case the package the HelloWorld.java file is in is com.wonder. You can see it from the first line

[java title=”HelloWorld.java” gutter=”true” highlight=”5″]
package com.wonder;
public class HelloWorld {
…..
[/java]

As you can see the file HelloWorldBrother class does not have an access modifier , but is accessible via the Helloworld class. However, if you define another class HelloWorldCousin.java in a different package say net.wonder, then HelloWorld will not be able to access it even if you import the package  as shown below.

Let’s first create a new package net.wonder and create a class HelloWorldCousin.java without specifying a default access modifier.

Now, lets see if we can instantiate the same from the HelloWorld class in the package com.wonder; Would this work ?

[java title=”HelloWorld.java” gutter=”true” highlight=”10″]
package com.wonder;
import net.wonder.*;

public class HelloWorld {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World !!");
HelloWorldBrother hwb = new HelloWorldBrother ();
HelloWorldCousin hwc = new HelloWorldcousin();

}

}
[/java]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s