Java member variable access constraints and scope

Member variable access limit

Java uses constraints on member variables to provide object-oriented features, encapsulation, and information hiding.

The member variable limiters provided by Java are public, private, and protected, and are available to the same package and subclass, unless they have separate access restrictions.

public

An object variable declared as public is always accessible when its class is accessible.

class Box {
  public int width;
  public int height;
  public int depth;
  public long idNum;
  static long boxID = 0;
  public Box() {
    idNum = boxID++;
  }
}

class PublicDemo {
  public static void main(String args[]) {
    Box mybox1 = new Box();
    Box mybox2 = new Box();
    mybox1.width = 7;
    mybox2.depth = 20;
  }
}

private

Object variables declared as private can be used only within the class to which they belong.

class Box {
  private int width;
  private int height;
  private int depth;
  ...
}

class PublicDemo {
  public static void main(String args[]) {
    Box mybox1 = new Box();
    mybox1.width = 7; //error
  }
}

protected

An object variable declared as protected can only be used in a class of the same package as a subclass of the class to which it belongs.

class Box {
  private int width;
  private int height;
  private int depth;
  protected int count; //Used in this class and its subclasses
  ...
}

class ProtectedDemo1 extends Box {
  //Create a subclass of the Box class using extends
  public static void main(String args[]) {
    Box mybox2 = new Box();
    mybox2.count = 7; //Accessible
  }
}

Effective range of variables

Variables can be separated by valid scope. Separating variables by their scope can be divided into member variables, method parameters and local variables, and exception handler parameters.

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post