Java Tutorial/Class Definition/Access Control

Материал из Java эксперт
Перейти к: навигация, поиск

Access Control: four access control modifiers

There are four access control modifiers in Java:

  1. public,
  2. protected,
  3. private, and
  4. the default access level.


A Superclass Variable Can Reference a Subclass Object

   <source lang="java">

class RefDemo {

 public static void main(String args[]) {
   BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
   Box plainbox = new Box();
   double vol;
   vol = weightbox.volume();
   System.out.println("Volume of weightbox is " + vol);
   System.out.println("Weight of weightbox is " + weightbox.weight);
   System.out.println();
   plainbox = weightbox;
   vol = plainbox.volume(); 
   System.out.println("Volume of plainbox is " + vol);
 }

} class Box {

 private double width;
 private double height;
 private double depth;
 Box(Box ob) { 
   width = ob.width;
   height = ob.height;
   depth = ob.depth;
 }
 Box(double w, double h, double d) {
   width = w;
   height = h;
   depth = d;
 }
 Box() {
   width = -1; 
   height = -1;
   depth = -1; 
 }
 Box(double len) {
   width = height = depth = len;
 }
 double volume() {
   return width * height * depth;
 }

} class BoxWeight extends Box {

 double weight;
 BoxWeight(BoxWeight ob) { 
   super(ob);
   weight = ob.weight;
 }
 BoxWeight(double w, double h, double d, double m) {
   super(w, h, d); 
   weight = m;
 }
 BoxWeight() {
   super();
   weight = -1;
 }
 BoxWeight(double len, double m) {
   super(len);
   weight = m;
 }

}</source>





Class Access Control Modifiers

  1. A class can have either the public or the default access control level.
  2. You make a class public by using the public access control modifier.
  3. A class whose declaration bears no access control modifier has default access.


Class Member Access Control Modifiers

Class members (methods, fields, constructors, etc) can have one of four access control levels:

  1. public,
  2. protected,
  3. private, and
  4. default access.



   <source lang="java">

Access Level From classes in other packages From classes in the same package From child classes From the same class public yes yes yes yes protected no yes yes yes default no yes no yes private no no no yes</source>



The default access is sometimes called package private.

Access levels to constructors are the same as those for fields and methods.


Class Member Access Matrix

   <source lang="java">

Private No modifier Protected Public Same class Yes Yes Yes Yes Same package subclass No Yes Yes Yes Same package non-subclass No Yes Yes Yes Different package subclass No No Yes Yes Different package non-subclass No No No Yes</source>





Composition with public objects

   <source lang="java">

class Engine {

 public void start() {}
 public void rev() {}
 public void stop() {}

} class Wheel {

 public void inflate(int psi) {}

} class Window {

 public void rollup() {}
 public void rolldown() {}

} class Door {

 public Window window = new Window();
 public void open() {}
 public void close() {}

} class Car {

 public Engine engine = new Engine();
 public Wheel[] wheel = new Wheel[4];
 public Door
   left = new Door(),
   right = new Door(); // 2-door
 public Car() {
   for(int i = 0; i < 4; i++)
     wheel[i] = new Wheel();
 }

} public class MainClass{

 public static void main(String[] args) {
   Car car = new Car();
   car.left.window.rollup();
   car.wheel[0].inflate(72);
 }

}</source>





Create a Singleton Object

   <source lang="java">

class MySingleton {

 // the static singleton object
 private static MySingleton theObject;
 private MySingleton() {
 }
 public static MySingleton createMySingleton() {
   if (theObject == null)
     theObject = new MySingleton();
   return theObject;
 }

} public class Main {

 public static void main(String[] args) {
   MySingleton ms1 = MySingleton.createMySingleton();
   MySingleton ms2 = MySingleton.createMySingleton();
   System.out.println(ms1 == ms2);
 }

}</source>





Default access level

When there is no access control modifier preceding a class declaration, the class has the default access level. Classes with the default access level can only be used by other classes that belong to the same package.

The Chapter class with the default access level is defined as follows.



   <source lang="java">

class Chapter {

   String title;
   int numberOfPages;
   public void review() {
       Page page = new Page();
       int sentenceCount = page.numberOfSentences;
       int pageNumber = page.getPageNumber();
   }

}</source>





In a class hierarchy, private members remain private to their class.

   <source lang="java">

// This program contains an error and will not // compile.

class A {

 int i; // public by default
 private int j; // private to A
  
 void setij(int x, int y) {
   i = x;
   j = y;
 }

}

class B extends A {

 int total;
 void sum() {
   total = i + j; // ERROR, j is not accessible here
 }

}

class Access {

 public static void main(String args[]) {
   B subOb = new B();
  
   subOb.setij(10, 12);
  
   subOb.sum();
   System.out.println("Total is " + subOb.total);
 }

}</source>





Private Override

   <source lang="java">

class PrivateOverride {

 private void f() {
   System.out.println("private f()");
 }
 public static void main(String[] args) {
   PrivateOverride po = new Derived();
   po.f();
 }

} class Derived extends PrivateOverride {

 public void f() {
   System.out.println("public f()");
 }

}</source>





Specifying Access Attributes

   <source lang="java">

import static java.lang.Math.sqrt; class Point {

 public Point(double xVal, double yVal) {
   x = xVal;
   y = yVal;
 }
 public Point(final Point aPoint) {
   x = aPoint.x;
   y = aPoint.y;
 }
 public void move(double xDelta, double yDelta) {
   x += xDelta;
   y += yDelta;
 }
 public double distance(final Point aPoint) {
   return sqrt((x - aPoint.x) * (x - aPoint.x) + (y - aPoint.y) * (y - aPoint.y));
 }
 public String toString() {
   return Double.toString(x) + ", " + y;
 }
 private double x;
 private double y;

}</source>





The protected keyword

   <source lang="java">

class A {

 private String name;
 protected void set(String nm) {
   name = nm;
 }
 public A(String name) {
   this.name = name;
 }
 public String toString() {
   return "I"m " + name;
 }

} class B extends A {

 private int i;
 public B(String name, int i) {
   super(name);
   this.i = i;
 }
 public void change(String name, int i) {
   set(name); // Available because it"s protected
   this.i = i;
 }
 public String toString() {
   return " " + i + ": " + super.toString();
 }

} public class MainClass {

 public static void main(String[] args) {
   B orc = new B("A", 12);
   System.out.println(orc);
   orc.change("B", 19);
   System.out.println(orc);
 }

}</source>



12: I"m A
 19: I"m B


The public Book class

   <source lang="java">

package yourpackagename; public class Book {

   String isbn;
   String title;
   int width;
   int height;
   int numberOfPages;

}</source>



The Book class is a member of the yourpackagename package and has five fields. Since Book is public, it can be instantiated from any other classes.

  1. A public class must be saved in a file that has the same name as the class, and the extension must be java.
  2. A Java source file can only contain one public class.
  3. A Java source file can contain other classes that are not public.


Understand the effects of public and private access

   <source lang="java">

class Test {

 int a; // default access
 public int b; // public access
 private int c; // private access
 void setc(int i) {
   c = i;
 }
 int getc() { 
   return c;
 }

} class AccessTest {

 public static void main(String args[]) {
   Test ob = new Test();
   ob.a = 10;
   ob.b = 20;
   ob.setc(100); 
   System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
 }

}</source>





Using Access Attributes

AttributePermitted AccessNo access attributeAccessible from methods in any class in the same packagepublicAnywhere as long as the class has been declared as publicprivateAccessible from methods inside the classprotectedAccessible from methods in the same package and from any subclass