• Post Reply Bookmark Topic Watch Topic
  • New Topic

Extends with generics.  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a situation like the following.Please help

--


--


--

A1 and A2 do not compile. I understand why. But, can I resolve this with generics? (i want A1 and A2 to share the method if possible)
--
A tried following, but didn't succeed.
public abstract class A {
public abstract void foo(Class<? extends B> b);
}
 
Ranch Hand
Posts: 74
5
Eclipse IDE Python Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct me if I am wrong but inheritance doesn't work that way. You cannot overwrite the method signature with another type and say it overrides the method declared in the supertype. You may specify the method signature as but you will have to stick to that signature in the sub classes.

Imagine you have: What would be the point in allowing only B1 as a parameter to foo? How should a caller know if someObject is an instance of A1 anyway and not A2? Your approach might not be the best if you don't want A1 to accept B2 and the other way around...

Generics are for parametrizing types and these do not exist at runtime (when the compiler creates the .class file). Your code however wouldn't work without generics so your compiler couldn't convert it (and thus it can't be contructed with the use of generics either).

You can also check this link for what is not possible in generics, it might get you a better idea how they work.
 
Ranch Hand
Posts: 76
3
IntelliJ IDE Java Windows
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This smells of flawed design. If you want to put restrictions on the type of parameters the implemented methods in the implementing classes can take, you are effectively breaking the contract established by the interface.

If you want to make the code COMPILE using generics, you can do it this way:

Here, class A is a parameterized type, and it can take any type that IS-A B. Both B1 and B2 fulfill this requirement, and classes A1 and A2 can be designed to require specific subclasses of B, as shown.
But this will gain you nothing. What you have here is two classes, implementing a common interface, but with which you cannot take advantage of polymorphism.

I guess, to really be able to answer your question, we need to know what you really want to achieve.
 
Petar Petrovic
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Christian and Kristian

Thank you for your answers and sorry for my late one.

This is something similar to what I needed.





 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!