Java的Modifier Types修饰符类型-笔记

本文深入探讨了Java中的访问控制修饰符(默认、私有、公共、受保护)、非访问控制修饰符(静态、最终)及其在类、方法、变量等元素上的应用规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

    • Classinterfaces 不能是 private
  • public:Visible to the world.

    • 接口:The fields in an interface are implicitly public static final and the methods in an interface are by default public
  • protected:Visible to the package and all subclasses.

    • classinterfaces 不能是 protected
    • interface 中的 methods 和 fields 不能是 protected

访问控制的继承规则

规则:不降级

  • 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;
    }
  • 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

    • 类:抽象类不能实例化出对象。一个类不能同时 既abstractfinal。一个类若含有abstract methods,则类必须申明为abstract

    • 方法:没有实现体(implementation,methods body),而将在子类中进行实现;只要子类不是 abstract,就须对从父类继承来的方法进行实现。抽象方法不能 finalstrict

    public abstract class SuperClass
    {
        abstract void m();  //abstract method
    }
    
    class SubClass extends SuperClass
    {
        // implements the abstract method
        void m()
        {
            ...
        }
    }
  • synchronizedvolatile,用于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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值