MST

星途 面试题库

面试题:Java中protected修饰符的使用场景及访问规则

请阐述Java中protected修饰符在类、成员变量、方法上的使用场景,并说明其访问规则,包括同包内和不同包下的情况。
18.7万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

1. 在类上的使用场景及访问规则

  • 使用场景protected修饰符不能用于修饰顶级类(即直接定义在包下的类),只能用于修饰内部类。内部类使用protected修饰,意味着该内部类对于同包内的其他类以及不同包下的子类可见。
  • 访问规则:同包内任何类可以访问protected修饰的内部类;不同包下,只有子类可以访问。例如:
package com.example;
public class Outer {
    protected class Inner {}
}
// 同包内访问
package com.example;
public class OtherClass {
    Outer.Inner inner = new Outer().new Inner();
}
// 不同包子类访问
package com.other;
import com.example.Outer;
public class SubClass extends Outer {
    Inner inner = new SubClass().new Inner();
}

2. 在成员变量上的使用场景及访问规则

  • 使用场景:常用于希望在子类以及同包内的其他类中能够访问该变量,但又不想对外完全公开的场景。比如,一个基类有一些数据,这些数据需要被子类使用,同时同包内的工具类可能也需要访问。
  • 访问规则
    • 同包内:同包内的任何类都可以访问protected修饰的成员变量。例如:
package com.example;
public class Base {
    protected int protectedVar;
}
package com.example;
public class AnotherClass {
    public void access() {
        Base base = new Base();
        int value = base.protectedVar;
    }
}
- **不同包下**:不同包下只有该类的子类可以访问`protected`修饰的成员变量。例如:
package com.example;
public class Base {
    protected int protectedVar;
}
package com.other;
import com.example.Base;
public class Sub extends Base {
    public void access() {
        int value = this.protectedVar;
    }
}

3. 在方法上的使用场景及访问规则

  • 使用场景:适用于一些方法是为子类继承和扩展而设计,同时同包内的其他类也可能需要调用的情况。比如,基类中有一些核心的处理逻辑,希望子类能重写扩展,同包内的辅助类也能调用。
  • 访问规则
    • 同包内:同包内的类可以调用protected修饰的方法。例如:
package com.example;
public class Base {
    protected void protectedMethod() {}
}
package com.example;
public class AnotherClass {
    public void call() {
        Base base = new Base();
        base.protectedMethod();
    }
}
- **不同包下**:不同包下只有该类的子类可以调用`protected`修饰的方法。例如:
package com.example;
public class Base {
    protected void protectedMethod() {}
}
package com.other;
import com.example.Base;
public class Sub extends Base {
    public void call() {
        this.protectedMethod();
    }
}