java - Java中基类中父类(super class)的 protected 方法会发生什么?

标签 java inheritance protected

我在 package1 中有一个 A 类,Bpackage2 中继承了 AA 包含方法 m1,它是 protected。现在我的疑问是,当我在另一个类 C 中创建 B 的对象时,它也是 package2B 的对象code> 无法访问方法 m1 为什么?下面是我的代码

package com.package1;

public class A {

    protected void m1(){
        System.out.println("I'm protectd method of A");
    }
}


package com.package2;

import com.package1.A;

public class B extends A {


    public static void main(String[] args) {

        B b = new B();
        b.m1();          // b object able to access m1

    }

}


package com.package2;

public class C {

    public static void main(String[] args) {

        System.out.println("Hi hello");
        B b = new B();
        b.m1(); //The method m1() from the type A is not visible

    }

}

父类(super class)的 protected 方法在子类中是否变为私有(private)方法?

最佳答案

来自 JLS 6.6.2. Details on protected Access

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

表示 protected修饰符指定该成员只能在其自己的包内访问(与 package-private 一样),此外,还可以由另一个包中其类的子类访问。

来自 Java Doc Controlling Access to Members of a Class
enter image description here


所以你可以访问方法m1从类 B即使它不在同一个包中,因为它是 A 的子类.
但是您无法访问方法 m1从类 C因为它与 A 不在同一个包中也不是 A 的子类.

因此,为了访问此方法,您可以创建方法 m1公开或移动你的类(class)C放入与类 A 相同的包中

关于java - Java中基类中父类(super class)的 protected 方法会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30207940/

相关文章:

java - 找出 System.out.printf 将打印出多少字符(通常)的简单方法

Java 继承与 super();

java - Java 中的 public、protected、package-private 和 private 有什么区别?

php - 使用 PHPUnit 测试 protected 方法的最佳实践(在抽象类上)

Java ReplaceAll 正则表达式具有相似的结果

java - 3D 到 2D 投影

java - 使用 jdbctemplate 插入查询给出异常 UncategorizedSQLException

c++ - 多层继承在 C++ 中有意义吗?

inheritance - 继承自 Java 类的 Kotlin 类是否也继承自 Any?

java - 使用反射实例化 protected 构造函数时出现 NoSuchMethodException