简体   繁体   中英

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. 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. While we're on the topic, having stringly typed getType() methods seems like a design error. 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). If emp is not referencing a Manager, that will throw a ClassCastException. Then you're free to invoke whatever you want on m.

Starting with java, uh.. 14? 15? You can shorten this:

if (emp instanceof Manager m) {
   // use m here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM