简体   繁体   English

从父类类型的字段访问子类方法

[英]Accessing child class method from parent-class-typed field

Consider these bogus classes: 考虑以下伪类:

A.java A.java

public class A {
    //
    // implementation...
    //
}

B.java B.java

public class B extends A {
    private Long id;

    public Long getId() {
        return id;
    };

    //
    // B specific implementation...
    //
}

C.java C语言

public class C extends A {
    private Long id;

    public Long getId() {
        return id;
    };

    //
    // C specific implementation...
    //
}

D.java D.java

public class D extends A {
    private Long id;

    public Long getId() {
        return id;
    };

    //
    // D specific implementation...
    //
}

E.java 电子书

public class E extends A {
    //
    // E specific implementation...
    //
}

Consider the case in which you cannot change these implementations and you have a field A a which will hold an object of type B , C or D and certainly there will be no case in which a hold an object of type A nor E . 考虑,可以在其中不改变这些实施方式的情况下,你有一个字段A a ,这将保持B,Cd的一个对象,并肯定会有任何情况下,其中a保持A也不-E类型的一个对象。

Is there a cleaner way, visually speaking, of accessing method getId() than: 在视觉上,是否有比以下方法更干净的方法来访问getId()

if (B.class.isInstance(a)) {
    return (Long) ((B) event).getId();
} else if (C.class.isInstance(a)) {
    return (Long) ((C) event).getId();
} else {
    return (Long) ((D) event).getId();
}

I know this is not possible, but something like this: 我知道这是不可能的,但是像这样:

public class X extends B, C, D {
    public Long getId() {
        return super.getId();
    }
}

I would use some interface here: 我会在这里使用一些接口:

interface HasId { 
    Long getId(); 
} 

and some custom B, C, D etc that implement it: 以及一些实现它的自定义B,C,D等:

class YourB extends B implements HasId {
    // nothing
}

class YourC extends C implements HasId {
    // nothing
}

// ...

then the problematic if becomes 那么问题 if变成了

if (a instanceof HasId) { 
    return ((HasId) a).getId();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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