简体   繁体   English

当孩子被归类为父母时,我可以访问孩子的方法吗?

[英]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.

相关问题 当父类是引用类型并通过方法传递时,如何从子类访问属性? - How can I access an attribute from a child class when the parent class is the reference type and passed through a method? 如何从父的静态方法调用child的静态方法? - How can i call child's static method from parent's static method? 如何从父母的方法访问孩子的继承成员 - How to access a child's inherited member from a parent's method 从C#中的子类访问父方法 - Access Parent's method from child class in C# 有没有一种方法可以在子类上实现可以从子类访问属性的方法? - Is there a way to implement a method on a child class that I can access the attributes from it's child? 如何在JAVA中从父类的内部类中调用子类中的重写方法? - How can I call the overridden method in a child class from a parent class's inner class in JAVA? 为什么我无法使用父类型访问子对象方法 - Why I cannot access Child Object method with Parent Type 如何访问父节点的孩子的孩子 - How to access a child's child of a parent Node 当父级的onInterceptTouchEvent()返回true时,我在哪里可以在子级中捕获ACTION_CANCEL? - Where can i capture the ACTION_CANCEL in child when parent's onInterceptTouchEvent() return true? 如果将子级添加为父级类,如何通过父级访问ArrayList中的子级对象? - How can I access a child object in an ArrayList through a parent if I added the child as the parent class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM