我在 package1
中有一个 A
类,B
在 package2
中继承了 A
。 A
包含方法 m1
,它是 protected
。现在我的疑问是,当我在另一个类 C
中创建 B
的对象时,它也是 package2
,B
的对象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
所以你可以访问方法m1
从类 B
即使它不在同一个包中,因为它是 A
的子类.
但是您无法访问方法 m1
从类 C
因为它与 A
不在同一个包中也不是 A
的子类.
因此,为了访问此方法,您可以创建方法 m1
公开或移动你的类(class)C
放入与类 A
相同的包中
关于java - Java中基类中父类(super class)的 protected 方法会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30207940/