如何解决为什么 ArrayList.removeRange() 在扩展 ArrayList 的 RoleList 类中不可见?
类protected void removeRange(int fromIndex,int toIndex)
中的方法:ArrayList
是protected
,所以我不能在ArrayList对象上调用它,但是我可以在一个扩展ArrayList的类的对象上调用它,如下面的代码所示。但是,我们在 Java API 中有扩展 ArrayList 的类,例如:javax.management.relation Class RoleList
为什么我不能像在我的类中那样在类型为 removeRange()
的对象上调用 RoleList
:ExtendsArrayList?
public class ExtendsArrayList extends ArrayList<Integer> {
public static void main (String[] args) {
ExtendsArrayList list = new ExtendsArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
// I can call removeRange() here.
list.removeRange(1,3);
RoleList rl = new RoleList();
rl.add(1);
rl.add(2);
rl.add(3);
rl.add(4);
rl.add(5);
// The method removeRange(int,int) from the type ArrayList<Object> is not visible
// Why its not visible in a class that extends ArrayList?
//rl.removeRange(1,3);
}
}
编辑:
为什么我应该扩展 RoleList
以使其工作? RoleList extends ArrayList
芳香四溢,为什么我不能指望在 removeRange()
的对象上调用 RoleList
才能正常工作?换句话说,当 ArrayList.removeRange()
对我的类的对象可见时,为什么 RoleList
对 RoleList extends ArrayList
类型的对象不可见:ExtendsArrayList extends ArrayList
? ExtendsArrayList
由我扩展,RoleList
由 Java API 扩展。
public class ExtendsRoleList extends RoleList {
public static void main (String[] args) {
RoleList rl = new RoleList();
rl.add(1);
rl.add(2);
rl.add(3);
rl.add(4);
rl.add(5);
// The method removeRange(int,int) from the type ArrayList<Object> is not visible
// Why its not visible in when RoleList that extends ArrayList?
//rl.removeRange(1,3);
ExtendsRoleList erl = new ExtendsRoleList();
erl.add(1);
erl.add(2);
erl.add(3);
erl.add(4);
erl.add(5);
// Why I should extend RoleList for this to work? Why its not visible when RoleList extends ArrayList automatically?
erl.removeRange(1,3);
}
}
解决方法
protected
表示它可以从子类在自身的上下文中调用; protected
并不意味着 class B1 extends A
可以在 A
上调用 class B2 extends A
的受保护方法。
示例:
class A {
protected void protectedMethod() {
//do something
}
}
class B1 extends A { //<-- we are extending A
public void someMethod() {
B1 b1 = new B1();
b1.protectedMethod(); //<-- you can call it because B1 extends A and you're in the context of B1
}
}
class B2 { //<-- we are not extending A
public void someMethod() { //<-- this method is exactly the same than above
B1 b1 = new B1(); //<-- B1 is still extending A
b1.protectedMethod(); //<-- though,you can't call the protected method anymore because you're not in the context of itself
}
}
,
rl.removeRange(1,3);
您试图从无法访问的外部包(外部 lang 包)访问 removeRange()
受保护的方法。所以编译器在抱怨它。
list.removeRange(1,3);
由于继承,您的类扩展了 ArrayList
,因此可以直接通过 protected 类修饰符访问覆盖或使用受保护的方法。
您正在调用您的对象的方法,该方法是通过父类继承的,现在可以被调用,因为它成为您自定义子类的一部分。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。