This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

best approach

 
Avtar Khalsa
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Guys

I have the following scenario and I'm not sure how best to avoid having copy and paste code:

Class A {
}

Class B extends A {
}

Class C extends A {
}

Class D extends B{
}

Classes A and B are part of a library that I can't change. Unfortunately, Class C and Class D are identical in every singe way. The fields are the same and the methods are the same with the same implementations. The only difference is that one extends class A and the other extends Class B.

I then have lots of classes that extend C or D throughout my program. The question is: is there any way to avoid having to copy and paste code from class C into class D? I have considered using an interface which C and D implement since that seemed like the obvious solution, however I need to have some of the fields and methods in C and D be private/protected which I can't do with an interface.

Any input would be much appreciated!


 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34672
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can C and D delegate to a common class that does the work?
 
Avtar Khalsa
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They can, however I think this will still leave me having to either write all the fields out twice, or making them public within the class that has been delagated to. Unfortunately, I really need these fields to be protected.
 
Stephan van Hulst
Bartender
Pie
Posts: 5895
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do all the classes really need to extend C or D? Can't you just use composition?

Inheritance is a powerful tool, but far too easily abused. Can you tell us the actual class names for A, B, C and D? This will help in determining if inheritance really is the solution.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic