Rodrigo Oliveira
Rodrigo Oliveira

Reputation: 1582

Accessing child class method from parent-class-typed field

Consider these bogus classes:

A.java

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

B.java

public class B extends A {
    private Long id;

    public Long getId() {
        return id;
    };

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

C.java

public class C extends A {
    private Long id;

    public Long getId() {
        return id;
    };

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

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.

Is there a cleaner way, visually speaking, of accessing method getId() than:

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();
    }
}

Upvotes: 0

Views: 68

Answers (1)

user180100
user180100

Reputation:

I would use some interface here:

interface HasId { 
    Long getId(); 
} 

and some custom B, C, D etc that implement it:

class YourB extends B implements HasId {
    // nothing
}

class YourC extends C implements HasId {
    // nothing
}

// ...

then the problematic if becomes

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

Upvotes: 1

Related Questions