当前位置: 技术问答>java相关
跨包之间访问protected类型的问题
来源: 互联网 发布时间:2015-01-26
本文导语: //file:PackagedClass.java package c05; public class PackagedClass{ public PackagedClass(){ System.out.println("Creating a packaged class"); } protected void f() { System.out.println("protedted access identifier"); } } //file:Foreign.java package c05.foreign; ...
//file:PackagedClass.java
package c05;
public class PackagedClass{
public PackagedClass(){
System.out.println("Creating a packaged class");
}
protected void f() {
System.out.println("protedted access identifier");
}
}
//file:Foreign.java
package c05.foreign;
import c05.*;
public class Foreign{
public static void main(String[] args) {
//PackagedClass pc = new PackagedClass();
//pc.f();
PackagedClassSub pcs = new PackagedClassSub();
pcs.f();
}
}
class PackagedClassSub extends PackagedClass {
public void test()
{
f();
}
}
编译时,pcs.f()出错,说:No method matching f() found in class c05.foreign.PackagedClassSub.
但是据我所知:子类(这里是PackagedClassSub)可以跨包访问父类(这里是PackagedClass)的protected方法f(),thinking in java书上也是这么说的,为什么会编译出错呢??
package c05;
public class PackagedClass{
public PackagedClass(){
System.out.println("Creating a packaged class");
}
protected void f() {
System.out.println("protedted access identifier");
}
}
//file:Foreign.java
package c05.foreign;
import c05.*;
public class Foreign{
public static void main(String[] args) {
//PackagedClass pc = new PackagedClass();
//pc.f();
PackagedClassSub pcs = new PackagedClassSub();
pcs.f();
}
}
class PackagedClassSub extends PackagedClass {
public void test()
{
f();
}
}
编译时,pcs.f()出错,说:No method matching f() found in class c05.foreign.PackagedClassSub.
但是据我所知:子类(这里是PackagedClassSub)可以跨包访问父类(这里是PackagedClass)的protected方法f(),thinking in java书上也是这么说的,为什么会编译出错呢??
|
你如果是想跨包访问的话,该用pcs.test();而不是pcs.f();
PackagedClassSub是PackagedClass的子类,可以访问PackagedClass的方法,但Foreign不是PackagedClass的子类,所以不能访问……
PackagedClassSub是PackagedClass的子类,可以访问PackagedClass的方法,但Foreign不是PackagedClass的子类,所以不能访问……
|
抱歉,该问题我也曾经疑惑过,但答案好象是如ender所说,由于Foreign不是packagedclass的子类,就算在他的代码中实现了对象,也不行。