Monday, February 10, 2014

Java / field, method: modifiers

Access to members of class.
Modifiers of field, method:

public
- is visible everywhere

private
- is visible only in owner class

protected
- is visible in owner class and subclass but only in the same package (and sub-package)

no-modifier (also known as package-private)
- is visible in owner class and subclass in the same package (not in sub-package)


EXAMPLES:

Modifier: public

package test;
class Car
{
 public String brand; // visible everywhere

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Possible use:

package test;
import test.Car;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // OK
  // OR
  tc.setBrand("Opel") // OK
 }  
}

Modifier: private

package test;
class Car
{
 private String brand; // visible only in own class

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Possible use:

package test;
import test.Car;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // field is not visible (Exception in thread "main" java.lang.Error: Unresolved compilation problems: )
  // But you can do that way
  tc.setBrand("Opel") // OK
 }  
}

Modifier: protected

package test;
class Car
{
 protected String brand; // visible only in package "test" and also in each sub-package of "test"

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Second class in sub-package

package test.subtest;
class SportCar extends Car
{
  
}

Possible use:

package test;
import test.Car;
import test.SportCar;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // OK    
    
  SportCar sportCar = new SportCar();
  sportCar.brand = "Ferrari";  // OK  
 }  
}

Modifier: no-modifier (package-private)

package test;
class Car
{
 String brand; // visible only in package "test" (not in sub-package of "test")

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Second class in sub-package

package test.subtest;
class SportCar extends Car
{
  
}

Possible use:

package test;
import test.Car;
import test.subtest.SportCar;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // OK    
    
  SportCar sportCar = new SportCar();
  sportCar.brand = "Ferrari";  // field is not visible 
 }  
}


Reference:
Java official tutorial

No comments: