OBJECT-ORIENTED PROGRAMMING
Java access modifiers
Access modifiers ( access modifiers) determine which parts of a program can use a class, attribute, method or constructor. They protect internal object state and clearly define a class's public interface.
Two groups of modifiers
- Access modifiers control where code is accessible:
public,privateandprotected. - Other modifiers provide other behavior, for example,
static ,finalorabstract.
This lesson focuses specifically on access levels.
Access to top-level classes
A top-level class can have public or package access by omitting the modifier:
| Access | Accessibility |
|---|---|
public | From any package, provided the class is properly imported |
| Package access | Only within the same package; no modifier is written |
// File: Knyga.java
public class Knyga {
// The class is also accessible from other packages
}
// No modifier specified – package access
class KnygosPagalbininkas {
// The class is accessible only within the same package
}These are only two class declarations. Neither class has a main() or println().
public class Knygacan also be used from other packages.- A public class's filename must match its class name:
Knyga.java. - For
KnygosPagalbininkas, no access modifier is written. - This class therefore has package access and can only be used by code in the same package.
default is not a keyword written here.“Default access” means that no access modifier is specified.
Access to attributes, methods and constructors
| Modifier | Same class | Same package | Subclass in another package | Other classes in another package |
|---|---|---|---|---|
private | ✅ Yes | ❌ No | ❌ No | ❌ No |
| (default) | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
protected | ✅ Yes | ✅ Yes | ✅ Yes* | ❌ No |
public | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
protected access from another package has an additional rule.A subclass accesses the member through inheritance: through itself or an instance of its own subclass. It cannot access a protected member through an arbitrary, separately obtained superclass object.
public and private example
A public book title is accessible from outside, but the read page count is kept within the class. External code obtains it through a public method:
class Knyga {
public String pavadinimas = "Mažasis princas";
private int perskaitytaPuslapiu = 40;
public int gautiPerskaitytusPuslapius() {
return perskaitytaPuslapiu;
}
}
public class Main {
public static void main(String[] args) {
Knyga knyga = new Knyga();
System.out.println(knyga.pavadinimas);
System.out.println(knyga.gautiPerskaitytusPuslapius());
}
}Mažasis princas
40
- The attribute
pavadinimasis markedpublic, soMainaccesses it directly. - The attribute
perskaitytaPuslapiuis markedprivate, so it cannot be accessed directly from outside. - The public method
gautiPerskaitytusPuslapius()runs inside the class itself and can read the private attribute. Maincalls this method and safely obtains the number40.
Direct use of the private attribute would look like this:
Knyga knyga = new Knyga();
System.out.println(knyga.perskaitytaPuslapiu);error: perskaitytaPuslapiu has private access in Knyga
- The code tries to access
knyga.perskaitytaPuslapiufrom outside theKnygaclass itself. - Modifier
privateallows the field to be used only within the class. - The compiler rejects the program, so this incorrect fragment produces no console output.
- The correct approach is to use the public method provided by the class.
Package access
With no modifier, a class member is accessible only within its package. This is useful for internal module details that need not be exposed to the whole program.
package lt.pavyzdys.knygos;
class KnygosPagalbininkas {
int puslapiuSkaicius = 96;
void rodytiPuslapius() {
System.out.println("Puslapių: " + puslapiuSkaicius);
}
}
public class Main {
public static void main(String[] args) {
KnygosPagalbininkas pagalbininkas = new KnygosPagalbininkas();
pagalbininkas.rodytiPuslapius();
}
}Puslapių: 96
- Both classes belong to the same package,
lt.pavyzdys.knygos. - For
KnygosPagalbininkas, its attribute and its method have no modifier. - This means all of them are accessible within the same package.
Maincreates a helper object and calls its method.- If
Mainwere in another package, this use would not be allowed.
What does protected actually allow?
protected is easiest to understand as two permissions combined. Any class in the same package can use the member. A subclass can also use it through inheritance, even from another package.
protected does not mean “accessible everywhere”. In another package, it specifically grants additional access to a subclass through inheritance.
The following classes are deliberately placed in two different packages. If they shared a package, the example would not show the key distinction of protected access:
// File: biblioteka/Leidinys.java
package biblioteka;
public class Leidinys {
protected String pavadinimas = "Mažasis princas";
protected void rodytiPavadinima() {
System.out.println(pavadinimas);
}
}
// File: parduotuve/Knyga.java
package parduotuve;
import biblioteka.Leidinys;
public class Knyga extends Leidinys {
public void rodytiInformacija() {
// Allowed because Knyga extends Leidinys
this.rodytiPavadinima();
System.out.println(this.pavadinimas);
System.out.println("Tai yra knyga");
}
public static void main(String[] args) {
Knyga knyga = new Knyga();
knyga.rodytiInformacija();
// Not allowed: in another package, a protected member
// cannot be accessed through a plain Leidinys object.
// Leidinys leidinys = new Leidinys();
// leidinys.rodytiPavadinima();
}
}Mažasis princas
Mažasis princas
Tai yra knyga
Leidinysis in the packagebiblioteka. It has theprotectedattributepavadinimasand the methodrodytiPavadinima().Knygais in another package,parduotuve, so the same-package rule alone does not help it.Knyga extends Leidinysmakes theKnygaclass aLeidinyssubclass.- Through inheritance, inside
Knygayou can writethis.rodytiPavadinima()andthis.pavadinimas. - The first line comes from the inherited method, the second from directly reading the inherited attribute, and the third from
Knygaclass itself. - However,
Knygacannot create an ordinaryLeidinysobject and use it to access theprotectedmethod. The commented lines would cause compilation errors.
| Modifier | Could Knyga use the member from another package? | Why? |
|---|---|---|
private | ❌ No | The member is directly accessible only within the Leidinys class. |
| Default access | ❌ No | Knyga is in another package. |
protected | ✅ Yes, through inheritance | Knyga is Leidinys subclass. |
public | ✅ Yes | A public member is accessible without a special subclass exception. |
private – class only; default access – package; protected – package and subclasses; public – everywhere.
Restricting constructor access
An access modifier can also control who may create instances of a class:
public class BibliotekosInformacija {
private BibliotekosInformacija() {
// Objects cannot be created from outside the class
}
public static void rodytiPavadinima() {
System.out.println("Miesto biblioteka");
}
public static void main(String[] args) {
BibliotekosInformacija.rodytiPavadinima();
}
}Miesto biblioteka
- The class constructor is marked
private, so other classes cannot writenew BibliotekosInformacija(). - However, the public
staticmethod belongs to the class itself and needs no object. - The method is called through the class name,
BibliotekosInformacija.rodytiPavadinima(). - This approach suits utility classes that provide only static operations or control their own object creation.
Which access level should you choose?
- Start with the narrowest access needed.
- Usually mark internal object attributes
private. publicReserve this for the deliberately designed class interface:protectedUse this only when inheriting classes genuinely need access to the member:- Package access suits internal cooperation between related classes in the same package.