Public
A .java file can have at most one class that is declared public.
- If present, this class must have the same name as the file.
A .java file can contain additional, non-public classes.
- This is generally considered a bad practice, however.
Drill¶
com.example.objs.drillsCreate a new class named just
A. InA.java, add the following outside the body ofclass A.* What happens if you removeclass B { }publicfrom the definition ofclass A? * What happens if you addpublicto the declaration ofclass B?
Practice Exercise¶
Later you will learn how to use inner classes: classes defined inside the body of another class.
public¶
A class, field, or method that is declared public can be seen and used by any other Java class.
Without public, a class can be seen and used only by other classes in the same package.
- These are the only two options for a class.
Fields, methods, and constructors can be declared with additional visibility modifiers which determine which other classes, if any, can access them.
| Modifier | Access |
|---|---|
| public | Methods of any class anywhere have access. |
| protected | Methods of subclasses and of any class in the same package have access. |
| (default) | Methods of classes in the same package (directory) have access |
| private | Only methods defined in the same class have access. |
- We will cover visibility in more detail later.
Drill¶
Objects/com.example.objs.drills.BankAppOpen and examine
BankApp, whoserunmethod declares and instantiates twoAccountobjects. Now openAccount. Change its two-argument constructor declaration frompublictoprivate. What happens when you save?Change the constructor declaration back to
public.