Method overloading using derived types as parameters in Java

Let's say I have existing code which I want to extend but also to avoid changing it as much as possible.

Somewhere around this code there is a method that receives some type.

Engine.method(Base b)

Now, I want to extend this functionality. So I extends Base into a type called Derived which holds some more data I need and I also implements another method that receives the Derived type and do something different with it.

Engine.method(Derived d)

But I don't want to change the original call to "method". I somehow managed to instansiate the correct type (Base or Derived) by using a flag but since the original call is taking the Base then my new method will not be called.

Base b = null; if(flag) { b = new Derived() } else{ b = new Base() } Engine.method(b)

The problem is that now my Engine.method(Derived d) will not be called. I worked-around it by using casting

if(flag) Engine.method((Derived)b)

But that's wrong and stupid. Any suggestions?

I can always do:

if(flag) { Engine.methodForBase(new Base()) } else{ Engine.methodForDerived(new Derived()) }

But can you think of something better?


-------------Problems Reply------------

Write this:

class Engine {
public static void method(Base argument) {
if (argument instanceof Derived) {
// ...
else {
// ...

But probably, you should extend your Engine class to allow for more polymorphism, e.g. do something like this:

interface Engine<T extends Base> {
void method(T argument);

And have implementations for Base and Derived like this:

class BaseEngine implements Engine<Base> {
public void method(Base argument) { ... }

class DerivedEngine implements Engine<Derived> {
public void method(Derived argument) { ... }

That happens because Java uses single dispatch. This ends meaning that in your case, the method called depends on the type of reference "b", which is Base, and not on the type of the instance that "b" holds. Therefore, method xpto.(Base b) will always be called.

You really have to cast it or use the last approach you wrote.

Why not simply call the method with a parameter of the correct type?

Base b = null;
if (flag) {
Derived d = new Derived()
Engine.method(d); // so the correct method will be used for Derived
b = d;
} else{
b = new Base()

You could also consider reusing the method(Base b):

public void method(Derived d) {

Category:java Views:0 Time:2011-07-25

Related post

  • Best way of structuring methods to handle derived types 2010-02-24

    I have an inheritance hierarchy similar to below and I want to write my DAL to persist these objects but am unsure as to the best way of structuring it? Pet <- Dog <- Alsation and Labrador Pet <- Cat <- Persian and Tabby Although all clas

  • Function/Method Overloading C++: Data type confusion? 2009-10-28

    I'm having some trouble overloading methods in C++. As an example of the problem, I have a class with a number of methods being overloaded, and each method having one parameter with a different data type. My question: is there a particular order in t

  • How do I write a generic method that takes different types as parameters? 2009-11-18

    I have the following extension method to add the elements in one collection to another collection: public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> list) { foreach (var item in list) { collection.Add(ite

  • Ambiguity between method overloads with string and EventHandler parameters 2011-01-12

    I'm having some difficulty with an overloaded method. My signatures look like this: void Register(object source, EventHandler mapped_handler) void Register(object source, string mapped_property) I'm trying to call the first one like this: Register(so

  • Scala: Method overloading over generic types 2011-02-13

    In C# I can overload methods on generic type as shown in the example below: // using System; using System.Collections.Generic; public class Test { public static void Foo(List<int> ints) { Console.WriteLine("I just print"

  • Static method calls to derived types over virtual implementations? (Android) 2010-07-08

    I have class A, with methods foo and bar, that are implemented by A1 and A2. The functionality in both A1 and A2 is the same. In other words: public class A { public int foo() { return 0; }; public int bar() { return 1; }; } class A1 extends A { publ

  • Preferred method for initializing a child class parameters in Java? 2009-08-27

    I have an application that takes some input and generates configuration files as output. Since the exact input or output format could change over time, I defined two interfaces: Importer and Exporter. Each concrete importer or exporter could have dif

  • C# Interface { T Func(T t);} : Generic Interfaces with Parameterized Methods with Generic Return Types 2009-10-26

    I thought I'd use some (what I thought was) simple generics to enforce CRUD on some Business Classes. eg. public interface IReadable <T> { T Read<T>(string ID); } and then perhaps, I could have a NoteAdapter to do C**R**UD with the Note c

  • Function overloading by return type? 2009-01-14

    Why don't more mainstream statically typed languages support function/method overloading by return type? I can't think of any that do. It seems no less useful or reasonable than supporting overload by parameter type. How come it's so much less popula

  • Method overloading in C with printf? 2011-08-31

    Possible Duplicate: What is the signature of printf? Does C support overloading? Does printf support function overloading In C? C's printf function seems to show method overloading as different types of arguments can be given to it. Is this right or

  • Method remove() of TreeSet type return 2012-02-25

    So I was looking at the method remove() from the class TreeSet, and the method has e return type boolean. The java api says that if the item we want to remove is in the tree, and is removed than the method returns true. What if the item is not in the

  • Is overloading really the only way to get default values for method parameters in Java? 2009-03-06

    I'm quite new to Java and from Python and PHP, I'm used to default values for function parameters. So I have a habit of writing methods that are designed to be called from slightly different situations where you want to set only some of the values. F

  • Method Overloading with Types C# 2009-10-22

    I was wondering if the following is possible. Create a class that accepts an anonymous type (string, int, decimal, customObject, etc), then have overloaded methods that do different operations based on the Type. Example class TestClass<T> { pub

  • Java - why no return type based method overloading? 2010-04-30

    I know this is not possible but can anyone provide a theory as to why Java chose not to support this? I am asking because I just ran into a situation where I think it would be nice to have. --------------Solutions------------- Because you are not req

  • What is the use of Method Overloading in Java when it is achieved by changing the sequence of parameters in the argument list? 2011-01-07

    I was reading a Java training manual and it said that Method Overloading in Java can be achieved by having a different argument list. It also said that the argument list could differ in (i). Number of parameters (ii). Datatype of parameters (iii). Se

  • C# Method Overload Problem With Class Derived From Generic Abstract Class 2011-04-06

    I am working on a project, and I have a generic abstract type that takes a type parameter that is itself derived from the abstract type. If you want to know why I would do this, please see this question. I have run into an interesting problem with ov

  • C# Optional Parameters or Method Overload? 2011-05-25

    This question already has an answer here: method overloading vs optional parameter in C# 4.0 [duplicate] 11 answers Since C# added optional parameters is it considered a better practice to use optional parameters or method overloads or is there a par

  • Understanding Scala method overloading, optional/default parameters for an API client lib 2011-06-10

    I'm trying to write a Scala client library for PrestaShop's Web Service and I'm having some trouble coming up with clean/user-friendly method definitions. Basically, I don't have a good enough understanding of Scala method overloading, optional/defau

  • up-casting in C# and call a specific method based on the derived type 2011-07-27

    I have a couple of classes, all derived from the same base type. class basetype{} class TypeA : basetype{} class TypeB : basetype{} ... A number of them is stored in a list. List<basetype> myObjects As always, each of these types has to be hand

Copyright (C), All Rights Reserved.

processed in 0.100 (s). 11 q(s)