• Post Reply Bookmark Topic Watch Topic
  • New Topic

Changing the parameter of a method while overriding - possible or not? (Generics maybe?)  RSS feed

 
Benjamin Knolle
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i am currently trying to learn to work with generics and I have the following situation:



As shown in the example code I have an abstract class with 3 oder 4 subclasses.
Now I have another abstract class that defines a method which has SuperA has a parameter and in the actual implementation I want to use different methods depending on what class the actual class of the parameter is, is that possible? Maybe with generics somehow?
Because I am pretty sure it won't work like this, the IDE gives me a possible infinite recursive emthod call warning, which I understand, I am just not sure what will happen when I run the programm, will it use the different method calls or not?
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The methods that you have written in SubB taking SubA1, SubA2 etc are not overriding the method in B. They are overloading it. Take the following code as an example:



This will call the method in SubB defined to take a SuperA, because the reference that is passed in is a SuperA. This code will cause a StackOverflowError because that method is recursively calling itself, as the compiler warned you. The other methods won't get called unless you pass in a reference of the appropriate type. The particular overload of a method that is called is determined at compile time by the compiler. You may be confusing this with polymorphic behaviour where the particular override of a method that is called is determined at runtime.

Java Generics won't help you here either, you can't specify type specific implementations of generic methods in Java like you can in C++. You may want to look up the Visitor Pattern though, because I think that might do what you want.

What is the specific problem you're trying to solve? There may be other better ways to address it.
 
Benjamin Knolle
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah I just tested the whole thing and it works just fine because thanks to overloading the method. It always calls the method for the specific parameter anyway.

I would have implemented it like this anyway, without the changeAttributes(SuperA a) but for some reason my task ask for me to implement abstract void changeAttributes(SuperA a) even if you can achieve the wanted result a lot smoother without it, in my humble opinion. I will ask my teacher the next time, why he wanted that exact implementation.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!