目录
1.1 前言
protected 关键字中文翻译就是受保护的访问修饰符。访问的范围是类中,包中和外部包中的子类。下面是详细内容,记得看实例代码的注释哦。
1.2 同一个包中
(1)同一个包同一个类中,直接调用 protected 修饰的变量或方法
class test {
protected void msg() {
System.out.println("understand?");
}
public static void main(String[] args) throws Exception {
test t = new test();
t.msg();
}
}
运行结果:
understand?
(2)同一个包中不同的类,实例化对象后直接调用 protected 修饰的变量或方法
package com.java; // 包 com.java
class A {
protected String msg = "Try to access the protected variable outside the class within the package";
}
public class ProtectedExample {
public static void main(String[] args) {
A a = new A();
System.out.println(a.msg); // 直接调用 A 类中被 protected 修饰的字符串 msg
}
}
运行结果:
Try to access the protected variable outside the class within the package
1.3 不同的包
(1)只有通过继承才能访问访问包外部被 protected 修饰的方法或变量
package com.java; //包com.java
public class A {
protected String msg = "Try to access the protected variable outside the package";
}
package com.javatpoint; //包com.jabapoint
import com.java.A; // 引入 com.java 包中的 A 类
public class ProtectedExample {
public static void main(String[] args) {
A a = new A();
System.out.println(a.msg); // 这里是错误的,msg 方法被 protected 修饰,不支持在别的包被调用
}
}
运行结果:(报错)
Exception in thread "main" java.lang.Error: Unresolved compilation problem:The field A.msg is not visible
(2)任何构造函数受 protected 修饰,则不能从包外部创建该类的实例
package test1;
public class test1 {
protected test1(){ // 错误在这里
System.out.println
("Try to access the protected method outside the package ");
}
}
package test2;
import test1.*;
public class test2 extends test1{
public static void main(String[] args){
test1 t = new test1();
}
}
运行结果:(报错)
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method msg() from the type A is not visible
1.4 不能将 protected 修饰外部类和接口
protected class ProtectedExample {
void display() {
System.out.println("Try to access outer protected class");
}
public static void main(String[] args) {
ProtectedExample p = new ProtectedExample();
p.display();
}
}
运行结果:(报错)
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
1.5 子类覆盖
如果将 protected 分配给任何方法或变量,则只能使用 public 或 protected 访问修饰符将该方法或变量覆盖为子类的方法或变量。
(1)用 public 覆盖
package test1;
public class test1 {
protected void a(){
System.out.println("test it");
}
}
package test2;
import test1.*;
public class test2 extends test1{
public void a(){ // 注意这里,用的是 public 修饰
System.out.println("Replace successfully");
}
public static void main(String[] args){
test2 t = new test2();
t.a();
}
}
运行结果:
public successfully
(2)用 protected 覆盖
package test1;
public class test1 {
protected void a(){
System.out.println("test it");
}
}
package test2;
import test1.*;
public class test2 extends test1{
protected void a(){ // 注意这里,用的是 protected 修饰
System.out.println("protected successfully");
}
public static void main(String[] args){
test2 t = new test2();
t.a();
}
}
运行结果:
protected successfully
1.6 总结