bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Classes
Java•Java Classes

Java Modifiers

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Modifiers?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Order

Put the learning moves in the order that makes the concept easiest to apply.

The public keyword is an access modifier , meaning that it is used to set the access level for classes, attributes, methods and constructors.
By now, you are quite familiar with the public keyword that appears in almost all of our examples:
Public vs. Private Example

Modifiers

By now, you are quite familiar with the public keyword that appears in almost all of our examples:

public
class Main

The public keyword is an access modifier , meaning that it is used to set the access level for classes, attributes, methods and constructors.

We divide modifiers into two groups

  • Access Modifiers - controls the access level
  • Non-Access Modifiers - do not control access level, but provides other functionality

Access Modifiers

For classes , you can use either public or default :

ModifierDescription
publicThe class is accessible by any other class
defaultThe class is only accessible by classes in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter

For attributes, methods and constructors , you can use the one of the following:

ModifierDescription
publicThe code is accessible for all classes
privateThe code is only accessible within the declared class
defaultThe code is only accessible in the same package. This is used when you don't specify a modifier. You will learn more about packages in the Packages chapter
protectedThe code is accessible in the same package and subclasses . You will learn more about subclasses and superclasses in the Inheritance chapter

Public vs. Private Example

In the example below, the class has one public attribute and one private attribute.

Think of it like real life

  • public - a public park, everyone can enter
  • private - your house key, only you can use it

Example

class Person {
  public String name = "John";   // Public - accessible everywhere
  private int age = 30;          // Private - only accessible inside this class
}
public class Main {
  public static void main(String[] args) {
    Person p = new Person();
    System.out.println(p.name);   // Works fine
    System.out.println(p.age);    // Error: age has private access in Person
  }
}

Example explained

Here, name is declared as public , so it can be accessed from outside the Person class. But age is declared as private , so it can only be used inside the Person class.

Previous

Java this

Next

Java Non-Access Modifiers