java 访问权限学习 —— Java Access Modifiers

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

  • Visible to the package. the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).

Default Access Modifier - No keyword:

Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.

Example:

Variables and methods can be declared without any modifiers, as in the following examples:

String version = "1.5.1";

boolean processOrder() {
   return true;
}

Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hide data from the outside world.

Example:

The following class uses private access control:

public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}

Here, the format variable of the Logger class is private, so there‘s no way for other classes to retrieve or set its value directly.

So to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, andsetFormat(String), which sets its value.

Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However if the public class we are trying to access is in a different package, then the public class still need to be imported.

Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Example:

The following function uses public access control:

public static void main(String[] arguments) {
   // ...
}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - protected:

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members‘ class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example:

The following parent class uses protected access control, to allow its child class override openSpeaker() method:

class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intension is to expose this method to its subclass only, thats why we used protected modifier.(提供给子类进行访问)

netty中的例子

abstract class AbstractNioSelector implements NioSelector {

    //NIO Selector
    protected volatile Selector selector;

    //内部任务队列
    private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<Runnable>();

    //selector循环
    public void run() {
        for (;;) {
            try {
                //处理内部任务队列
                processTaskQueue();
                //处理selector事件对应逻辑
                process(selector);
            } catch (Throwable t) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // Ignore.
                }
            }
        }
    }

    private void processTaskQueue() {
        for (;;) {
            final Runnable task = taskQueue.poll();
            if (task == null) {
                break;
            }
            task.run();
        }
    }

    protected abstract void process(Selector selector) throws IOException;

}
abstract class AbstractNioWorker extends AbstractNioSelector implements Worker 

protected void process(Selector selector) throws IOException {
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        if (selectedKeys.isEmpty()) {
            return;
        }
        for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) {
            SelectionKey k = i.next();
            i.remove();
            try {
                int readyOps = k.readyOps();
                if ((readyOps & SelectionKey.OP_READ) != 0 || readyOps == 0) {
                    if (!read(k)) {
                        // Connection already closed - no need to handle write.
                        continue;
                    }
                }
                if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                    writeFromSelectorLoop(k);
                }
            } catch (CancelledKeyException e) {
                close(k);
            }

            if (cleanUpCancelledKeys()) {
                break; // break the loop to avoid ConcurrentModificationException
            }
        }
    }

Access Control and Inheritance:

The following rules for inherited methods are enforced:

  • Methods declared public in a superclass also must be public in all subclasses.
  • Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
  • Methods declared without access control (no modifier was used) can be declared more private in subclasses.
  • Methods declared private are not inherited at all, so there is no rule for them.
时间: 2024-01-08 01:40:59

java 访问权限学习 —— Java Access Modifiers的相关文章

java访问权限整理

类实例化成对象之后,可以通过对象加上"."操作符访问和操纵该对象的域和方法,但是这种访问是有限制的,通过public.protected.default(啥都不写).private来控制. 先看一个实验的例子:(不注释表示可以访问,注释掉表示无法访问) package packageA; import packageB.SubB; public class Base { public String publicStr = "publicString"; protec

论Java访问权限控制的重要性

人在什么面前最容易失去抵抗力? 美色,算是一个,比如说西施的贡献薄就是忍辱负重.以身报国.助越灭吴:金钱,算是另外一个,我们古人常说"钱乃身外之物,生不带来死不带去",但我们又都知道"有钱能使鬼推磨". 除去美色和金钱,我认为还有一个,就是读者的认可--"二哥,你的文章真的很棒,我特别喜欢.希望能多多更新Java基础知识,真的是受益良多,就好像是在读王小波的散文,但又学了编程!"--你说,收到读者这样暖暖的评语,还需要美色和金钱?"两者

Java访问权限控制

访问权限控制   java提供了访问权限修饰词,以供类库开发人员向客户端程序员指明哪些是可用的,哪些是不可用的.访问权限控制的等级,从最大权限到最小权限依次是:public.protected.包访问权限(没有关键字).private. 包:库单元 包内有一组类,它们在单一名字空间之下被组织在了一起.如果你向导入某个标准库中的类的话,可以使用import关键字.我们之所以要导入,就是要提供一个管理名字空间的机制.所有类成员的名称都是彼此分离的.所以具有相同方法的不同类在程序运行时不会出现错误的.

Java 访问权限控制:你真的了解 protected 关键字吗?

摘要: 在一个类的内部,其成员(包括成员变量和成员方法)能否被其他类所访问,取决于该成员的修饰词:而一个类能否被其他类所访问,取决于该类的修饰词.Java的类成员访问权限修饰词有四类:private,无(默认情况下,包访问权限),protected 和 public,而其中只有包访问权限和public才能修饰一个类(内部类除外).特别地,很多的介绍Java的书籍对protected介绍的比较笼统,常常会对大家造成误解.因此,本文重点揭示了 protected 关键字的内涵和用法,并介绍了一些其他

java访问权限的问题

java访问权限的问题 java 访问权限 修饰符 背景: 关于java中的四种访问修饰符,public ,default ,protected ,private的作用范围本以为很熟悉了,但碰到了这样一段代码: package pac1; public class Parent { protected int i; protected class Inner{ } } package pac2; import pac1.Parent; public class Child extends Par

Java访问权限控制小结

进行访问权限控制的两个原因 第一,可以控制类成员的可见性,使客户程序员只看到应该看到的内容 第二,可以使类的创建者随意改变类内部的工作方式,而不必担心会对客户端程序产生重大影响 四种访问权限 pulic 默认(包权限) protected private 用于域和方法 public表示所有人对本成员都可以访问 默认访问权限表示同一包下的类可以对本成员进行访问,其他包中的则不可以(!默认包) protected用于类的继承中,protected提供包访问权限,同时,子类也对protected成员具

[THINKING IN JAVA]访问权限控制

6 访问权限控制 6.1 包:库单元 package.import.import *.import static: 修改classpath环境变量可以将自己写的类库添加至环境变量并在任何java程序中import: 6.2  JAVA访问权限修饰符 访问权限:public>protected>包访问权限(没有限定词)>private: public:任何类在任何地方均可访问: 默认包:没有声明package并且处于同一目录下,则他们隶属于默认包,处于同一个package下: protec

Java泛型通配符学习 —— Java Generic&#39;s Wildcards

Java Generic's wildcards is a mechanism in Java Generics aimed at making it possible to cast a collection of a certain class, e.g A, to a collection of a subclass or superclass of A. This text explains how. 理解:Java的泛型通配符机制旨在实现集合的类型转换.例如集合A,转换为A的子类集合或

Java访问权限修饰符Java Access Modifiers

 访问权限的修饰符一共有四种: private,默认(default),protected,public  能修饰类.方法和属性上的修饰符有哪些呢     访问权限修饰符对方法和属性的控制范围 通常情况下类一般设置为public,属性一般设置为private,方法一般设置为public (也有少数使用protected,private) 原文地址:https://www.cnblogs.com/seviyan/p/11616846.html