Java Modifier Types修饰符类型
本文参考这里
- Access Modifiers
- Non Access Modifiers
Access Control Modifiers 访问控制
default:Visible to the package, the default. No modifiers are needed.private:Visible to the class only.- Class 和 interfaces 不能是
private
- Class 和 interfaces 不能是
public:Visible to the world.- 接口:The fields in an interface are implicitly
public static finaland the methods in an interface are by defaultpublic
- 接口:The fields in an interface are implicitly
protected:Visible to the package and all subclasses.- class 和 interfaces 不能是
protected - interface 中的 methods 和 fields 不能是
protected
- class 和 interfaces 不能是
访问控制的继承规则
规则:不降级
- 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.
Non Access Modifiers
static- 变量:Local变量不能
static - 方法
private static int cnt = 0; public static int getCount() { return cnt; }- 变量:Local变量不能
final- 变量:只能显式初始化一次,不能再赋值,
final int var = 10; - 方法:不能被重写(A final method cannot be overridden by any subclasses)
public class Test{ public final void changeName(){ // body of method } }- 类:不能被继承
public final class Test { // body of class }- 变量:只能显式初始化一次,不能再赋值,
abstract类:抽象类不能实例化出对象。一个类不能同时 既
abstract又final。一个类若含有abstract methods,则类必须申明为abstract方法:没有实现体(implementation,methods body),而将在子类中进行实现;只要子类不是
abstract,就须对从父类继承来的方法进行实现。抽象方法不能final或strict。
public abstract class SuperClass { abstract void m(); //abstract method } class SubClass extends SuperClass { // implements the abstract method void m() { ... } }synchronized和volatile,用于threads- synchronized
// method can be accessed by only one thread at a time public synchronized void showDetails() { ... }- transient
public transient int limit = 55; // will not persist public int b; // will persist- volatile
private volatile boolean active; // 线程1 public void run() { active = true; while (active) { ... } } // 线程2 public void stop() { active = false; }
本文深入探讨了Java中的访问控制修饰符(默认、私有、公共、受保护)、非访问控制修饰符(静态、最终)及其在类、方法、变量等元素上的应用规则。
728

被折叠的 条评论
为什么被折叠?



