Object Oriented

Visibility

Java

 

Visibility

Java 8
class Person {
  
  public String name;
  protected String fingerprint;
  
  private void debug() {}
  
}

Access Modifier are an added control over properties and methods to specify from where they can be accessed.

There are 4 types of access modifiers in Java:

  • public
  • Default (no keyword specified)
  • protected
  • private
 

Public

Java 8
class Person {
  
  // ...
  
  public String name;
  
  public void greet() {
    System.out.println("Hi! I'm " + name);
  }
  
}

public properties and methods can be accessed from:

  • Anywhere outside of a class which they are declared
  • Within the class that they are declared
  • From any class inheriting the current class they are declared in.

In other word, public properties and methods can be accessed from anywhere.

 

Protected

Java 8
class Person {
  
  // ...
  
  protected String fingerprint;
  
  protected void setFingerprint(String fingerprint) {
    this.fingerprint = fingerprint;
  }
  
}

protected properties and methods can be accessed from:

  • Outside of class but inside a Package which they are declared
  • Within the class that they are declared
  • From any class inheriting the current class they are declared in, even if those classes are in different Packages.

So if Teacher class inherits from Person, then it has access to fingerprint property and setFingerprint() method.

 

Private

Java 8
class Person {
 
  // ...
  
  private int person_id;
    
  private void debug() {
    System.out.println("person_id: " + person_id);
  }
  
}

private properties and methods can be accessed from:

  • Within the class that they are declared

So if Teacher class inherits from Person, then it can't read or set the $person_id property or call debug() method from a Person class.

 

Default

Java 8
class Person {
  
  // ...
  
  String name;
  
  void greet() {
    System.out.println("Hi! I'm " + name);
  }
  
}

properties and methods with no Access Modifier get a package-private visibility. They can be accessed from:

  • Outside of class but inside a Package which they are declared
  • Within the class that they are declared
  • From any class inheriting the current class they are declared in, if they are in a same Package.

Visibility of Default Access Modifier for Interface is public.