【发布时间】:2017-09-06 21:20:02
【问题描述】:
我正在阅读有关 Java 7 认证的 OCA 和 OCP 的书,我正在尝试使用 Java 8 进行本书的练习,我注意到一些连线。
我有 Class1 类如下:
package cert;
public class Class1{
protected static void importantMethod(){
System.out.println("importantMethod() method of Class1 class TEST \n");
}
importantMethod() 方法的修饰符是 protected static 并且包是 cert 如您所见,如书中所述我希望另一个包中的另一个类,在我的例子中显示如下 Class2,只能通过继承访问 importantMethod() 方法,但事实证明,来自 Class2 我也可以通过 Class1 的实例访问 importantMethod() 方法。
Class2 类:
package exam;
import cert.Class1;
class Class2 extends Class1 {
public static void main(String[] args) {
Class1 c1 = new Class1();
c1.importantMethod();
}
}
如果我从 Class1 中删除 static 修饰符,则在尝试从 importantMethod() 方法访问时会出现预期错误>Class2:
exam\Class2.java:7: error: importantMethod() has protected access in Class1
c1.importantMethod();
^
我的问题是,非访问修饰符会改变类成员的访问级别吗?
【问题讨论】:
-
"Class1 的修饰符是protected static"...你的问题清楚地显示为
public -
@cricket_007 他应该指的是方法“importantMethod”的修饰符。
-
静态成员是类的属性,非静态成员是对象或实例的属性。快速回答是否定的,
static不会更改访问级别,而是更改访问的类型。 -
嗨@DrewKennedy,所以我可以通过Class1的实例访问importantMethod而不是作为继承的成员对吗?
标签: java access-modifiers ocpjp