[英]Can I access a child's method when it is classified as a parent?
For example, I have an arraylist of objects that are all the parent type, but I want to access the child methods for one of the elements.例如,我有一个 arraylist 对象,这些对象都是父类型,但我想访问其中一个元素的子方法。 This is the code I have:这是我的代码:
ArrayList<Employee> staff = new ArrayList<Employee>();
for (Employee emp : staff) {
if (emp.getType().equalsIgnoreCase("Manager")) {
//use a method from the manager class with emp
}
}
You'd have to make a type assertion, using the cast construct.您必须使用 cast 构造进行类型断言。 While we're on the topic, having stringly typed getType()
methods seems like a design error.当我们讨论这个话题时,使用字符串类型的getType()
方法似乎是一个设计错误。 That should either be an enum, or you can get rid of it altogether.那应该是一个枚举,或者你可以完全摆脱它。 Assuming you have:假设你有:
class Employee {}
class Manager extends Employee {}
then:然后:
for (Employee emp : staff) {
if (emp instanceof Manager) {
Manager m = (Manager) emp;
m.doManageryThings();
}
}
The (Manager) emp
part is a type assertion: It acts like m = emp
(which ordinarily wouldn't be a legal statement, but it is with this cast. It's the same object, but, now assigned to a variable of the type you wanted). (Manager) emp
部分是一个类型断言:它的作用类似于m = emp
(通常不会是法律声明,但它是这种强制转换。它是相同的 object,但现在分配给类型的变量你自找的)。 If emp
is not referencing a Manager, that will throw a ClassCastException.如果emp
没有引用管理器,则会抛出 ClassCastException。 Then you're free to invoke whatever you want on m.然后你可以自由地在 m 上调用任何你想要的东西。
Starting with java, uh.. 14?从 java 开始,嗯.. 14? 15? 15? You can shorten this:你可以缩短这个:
if (emp instanceof Manager m) {
// use m here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.