Nikolaos Zormpas
Nikolaos Zormpas

Reputation: 57

Is type casting to super class and calling an overriden method acceptable? (Java)

It seems to work but is it concidered 'good' programming?

Here is an example to clarify:

public class foo{
   foomethod(){do something};
}

public class foo1 extends foo{
    @override foomethod(){do something};
}

public class foo2 extends foo{
    @override foomethod(){do something};
}

ArrayList x /*with foo1 and foo2 objects*/
for (Object o : x){((foo)o).foomethod();}

is this concidered 'good' programming and if not what is a nice compact alternative? (apart from switch(o.getClass()) if possible)

edit because I am really bad at clarifying it seems :)

I do mean to call the method that has been overriden and not the super method. An alternative method for what I want to do would be:

ArrayList x /* again with foo1 and foo2 objects*/

for (Object o : x){
    switch(o.getClass()){
        case foo1.class:
            ((foo1)o).foomethod();
            break;
        case foo2.class:
            ((foo1)o).foomethod();
            break;
    }
}

but I want to avoid the switch statement because it makes the code much bigger and complex.

Upvotes: 2

Views: 1952

Answers (3)

Stephen C
Stephen C

Reputation: 718758

It seems to work but is it concidered 'good' programming?

Modulo the problem with the wording of your question ...

Yes, it is good programming to declare a method in a superclass, override it in a subclass, and call it polymorphicly.

It is certainly much better than using a chain of instanceof tests or a switch on the class name. Those approaches are considered "bad" ... because they involve wiring too much knowledge of the class hierarchy into other code. For instance, if you add another subclass of Foo, all of those switches need to be checked and potentially changed. (And the compiler won't remind you to do it ...)

Upvotes: 1

Charlie
Charlie

Reputation: 7349

You probably want to use Generics:

public class Foo{
   public void fooMethod(){ System.out.println("Foo");};
}

public class Foo1 extends Foo{
    @Override public void fooMethod(){System.out.println("1");};
}

public class Foo2 extends Foo{
    @Override public void fooMethod(){System.out.println("2");};
}

...

List<Foo> x = new ArrayList<Foo>();
x.add(new Foo1());
x.add(new Foo2());
x.add(new Foo());

for (Foo o : x){ o.fooMethod();}

Output would be:

1
2
Foo

Upvotes: 2

user207421
user207421

Reputation: 310884

Whether it's considered acceptable or not is entirely beside the point. The real problem is that it doesn't do what you seem to think it does. It doesn't 'call an overridden method'. The derived class's method is still called. If you want to call the overridden method, you have to use the super keyword from within the derived class.

Upvotes: 2

Related Questions