java coding adventure

Getting lost on the trail: what when there’s no keyword?

But Calculator’s attributes have no keyword!

In last adventure, I told you that you can use the public keyword in class declaration or before every class member: attribute and method. When something is public it’s known everywhere. You’ve seen public class and public methods.

Then you looked at the code and you’ve noticed:

public class Calculator {

	String producentName = "Casio";
	String model = "fx-350ES PLUS";

And you probably want to ask: what if there’s no keyword?

What if there’s no keyword?

No keyword means the access modifier is default. When you use default access modifier you can use classes and class members only inside the package with the same name.

The package

Package is a folder where you put your *.java files. It is specified in the begginign of every java file:

 package blog.jumpstart.learningPath;

You can see it in the project view:

package

Code example

You can use model and producentName in class Potato:

package blog.jumpstart.learningPath;

public class Potato {

	public static void main(String[] args) {
		Calculator calculator = new Calculator();
		System.out.println(calculator.add(1, 2));
		System.out.println(calculator.model);
		System.out.println(calculator.producentName);
	}

}

but, if you try to use it in a different package you’ll get an error. The Calculator project has no other package, but you can create one (right click on the source folder src/main/java > new > package) and than create there a class with the main method. The incorrect usage of an attribute with the default access modifier would look like this (pay attention to the package written in the first line):

package blog.jumpstart.potato;
import blog.jumpstart.learningPath.Calculator;
public class Potato {

	public static void main(String[] args) {
		Calculator calculator = new Calculator();
		//line below will work fine: add is a public method
		System.out.println(calculator.add(1, 2));
		//line below will give you an error
		System.out.println(calculator.model);
	}
}

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