java coding adventure

Visit in the museum: access level – public (and what it means in Java)

Class declaration

Do you remember class declaration of Calculator?

 public class Calculator 

You know it’s a class because of the keyword class before the class name.

But what’s the public there?

Imagine your Java project is a town and every class is a building. In the town, everyone can visit public places like the museum or the cafe. Everyone knows where the public places are (or can easily find out) and what those places do. The same is with public classes in Java. Everyone can use a public class and it can be accessed from every place in a project (as you can access the museum from every part of the city)

Access level modifier: public

The keyword public is called access level modifier. You see the public access level modifier not only in class declaration but also before each method both in class Calculator and in CalculatorTest:

public int add(int summand1, int summand2) {
    return summand1+summand2;
}

You can use access level modifiers before every class member: each method and each attribute.

Where to use what’s declared public?

Everything that is public is well-known and doesn’t matter where you are in the town you know where the public place is and you can access it.

It’s the same with the public classes, methods and attributes. You can use public classes and public class members everywhere.

Because the method public int add(int summand1, int summand2) is public, you can use it in the class CalculatorTest:

@Test
public void sum() {
    Calculator calculator = new Calculator();
    Assert.assertEquals(3, calculator.add(1, 2));
}

or in the main function in class Potato:

public class Potato {

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        System.out.println(calculator.add(7, 8));
    }

}

 

1 thought on “Visit in the museum: access level – public (and what it means in 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