Enter vs instanceof variable for identification

I have two classes that are subclasses of an abstract class A:

class X extends A {}
class Y extends A {}

I would like to identify a subclass of the object Apassed to the function. I see two alternatives:

void myfunction(A myobj) {
    if(myobj instanceof X)
        doXStuff((X) myobj);
    if(myobj instanceof Y)
        doYStuff((Y) myobj);
}

or add enumin Awith different types:

abstract class A {
    enum Type { X, Y };
    Type type;
    ...
}

class X extends A {
    type = Type.X;
    ...
}
class Y extends A {
    type = Type.Y;
    ...
}

void myfunction(A myobj) {
    if(myobj.type == Type.X)
        doXStuff((X) myobj);
    if(myobj.type == Type.Y)
        doYStuff((Y) myobj);
}

What's better? I am inclined to the second, because it is instanceofnot suitable for a production application. Is there any other better way? If the second is better, is it better to post enum?

+4
source share
2 answers

Both are bad.

A, X Y . , - .

abstract class A {
    void doStuff();
}

class Y extends A {
    @Override
    void doStuff() {
        // Y specific implementation
    }
}

class X extends A {
    @Override
    void doStuff() {
        // X specific implementation
    }
}

void myfunction(A myobj) {
    myobj.doStuff();
}
+7

: " ".

, , .

, . X Y, Client, X Y.

, .

do_stuff(Object generic_data){((cast_so_special_class)generic_data).do_something_spcial_class_specific();}
0

Source: https://habr.com/ru/post/1569495/


All Articles