1

我有 3 节课,首先是 Person :

public class Person {    
    Person() {

    }
}

二是人的延伸工程师

public class Engineer extends Person { 
    Engineer() {

    } 
}

和 Person 的另一个延伸

public class Doctor extends Person {
    Doctor() {

    } 
}

最后一个是接受构造函数 Person 的 Work

public class Work {
    Work(Person p) {
    //how to insure that p is Engineer ?
    }
}

如何检测对象 p 是 Engeneer 而不是来自另一个类?

4

7 回答 7

6

您可以使用instanceof关键字来检查对象的类型。它像这样工作

if(p instanceof Engineer) {
   // do Engineer stuff
} else {
   // not an Engineer object
}
于 2012-05-03T07:57:23.570 回答
2

您可以通过以下方式进行检查:

if (p instanceof Engineer)

或者

if (p.getClass() == Engineer.class)
于 2012-05-03T07:57:55.847 回答
1

使用类似的东西:

if (p.getClass() == Engineer.class) {
    //Is engineer
}
于 2012-05-03T07:57:13.050 回答
1
public class Work {

    // ensure only Engineer can pass in
    Work(Engineer p) {

    }
}

或使用instanceof关键字

运算符将instanceof对象与指定类型进行比较。您可以使用它来测试对象是类的实例、子类的实例还是实现特定接口的类的实例。

public class Work {

    Work(Person p) {
        // make sure p is type of Engineer
        if(p instanceof Engineer) {
            // dowork
            Engineer e = (Engineer) p;
        } else {
            // not engineer or p is null
        }
    }
}
于 2012-05-03T07:57:21.070 回答
1
p.getClass() 

(从那里开始,.getName()

或操作员instanceof(注意,医生和工程师将返回instanceOf Person为真;检查更具体的类)

于 2012-05-03T07:57:54.063 回答
1

你不应该这样做。

Work(Engineer p) {
    // p is an Engineer
}

或者

Work(Person p) {
    p.doWork(); // calls the appropriate work methopd for any person.
}
于 2012-05-03T07:58:13.860 回答
1

使用 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 .

于 2012-05-03T07:58:33.227 回答