• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class Design - define methods that all subclasses have in common.  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I recently encountered the following problem: I got an abstract class, A, and several (non-abstract) subclasses of A: X, Y, ...
I want to make sure all subclasses of A (name: Z extends A) can calculate distances between each other. In other words: Each subclass Z has to have a method "double distanceTo(Z)". Now, I can't find a way to ensure this. Can you help me out, explain me why it is not possible, or give me a hint what can be done instead?

Thanks!
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try adding the method:
to your class Z. This will require that all your subclasses implement the distanceToZ() method (if they themselves are not declared as abstract).
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To ensure that you can only calculate the distance between instances of the same class, make your base class generic:
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And to reduce confusion between a class and generic type, I suggest changing the following:
I also got rid of a compiler warning by specifying <E extends A<E>>
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah right, missed that one. I usually use T though; I reserve E for element types, T for others.
 
S Lei
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great Thanks. I solved it with generic types, too in the meanwhile. Although, I missed the last hint, too, and now everything feels right.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!