使用 instanceof 关键字
if(p instanceof Engineer) {
// do something
}
if(p instanceof Doctor) {
// do something
}
但这不是正确的方法,您应该在工程师类中具有工程师的行为(方法),在博士类中具有医生的行为。
请参阅彼得的回答,运行时多态性将检测自动调用哪个方法。
IE
class Engineer extends Person {
// properties
// methods
public void doWork() {
// does engineering work
}
}
class Doctor extends Person {
// properties
// methods
public void doWork() {
// does doctor work like check patients, operation or other his task
}
}
class Work {
Work(Person p) {
p.doWork(); // if you pass engineer obj here, Engineer.doWork() is called. And if you pass doctor, Doctor.doWork() is called.
// You don't need to use instanceof.
}
}
在上述情况下,Engineer 和 Doctor 具有相同的方法名称,但在某些情况下您可能需要使用 instanceof,例如 Doctor 将具有 checkPatient() 方法,Engineer 将具有一些不同的方法名称,例如 designEngine(),那么您将不得不使用 instanceof .