Is this an example of good practice?

I have a list of objects that extend from the base class. Now I want to apply a specific operation to only one instance of the classes in the list.

Is using instanceofgood practice there? Or should I distinguish between objects, for example, custom ones enum?

abstract class Base;
class Foo extends Base;
class Bar extends Base;

List<Base> bases;

for (Base base : bases) {
  if (base instanceof Bar.class) {
     //execute my custom operation on the base object
     doSomething((Bar) base);
  }
}

If this approach is not so good overall, how can I do better?

+5
source share
3 answers

. , , , . , , ( , , ). :

abstract class Base{
    public void doSomething(){}
}

public class B0 extends Base{
    @Override
    public void doSomething(){//actually do something}
} 

public class B1 extends Base{}

- :

public class SomeOtherClass{
    public void something(List<Base> bases){
         for(Base base:bases)
             base.doSomething();
    }
}
+3
abstract class Base;//abstract function doSomething()
class Foo extends Base;//implements doSomething()
class Bar extends Base;//dito

List<Base> bases;

for (Base base : bases) {
     base.doSomething();
}

: instanceof.

+2

.

, doSomething. -, , , . , , - -, , , doSomething. , , . , doSomething , - no operation. , , , .

You should also ask yourself if you really need a base class for an abstract class. Perhaps all you need is an interface. There may be a better approach, but based on the information I have and what I suggested, then it seems to be all right.

public abstract class Base
{
    public abstract void doSomething();

    public void someOtherMethod()
    {
        // which does stuff
    }
}

public class SubTypeWhichCanDoSomething extends Base
{
    @Override
    public void doSomething()
    {
        // actually implement method and DO something
    }
}

public class DoesNothing extends Base
{
    @Override
    public void doSomething()
    {
        // does nothing
        return;
    }
}

// then your code looks like these
for(Base base : bases)
{
    base.doSomething();
}
+1
source

All Articles