Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes best approach Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "best approach" Watch "best approach" New topic
Author

best approach

Avtar Khalsa
Greenhorn

Joined: Jul 02, 2008
Posts: 3
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

Joined: May 26, 2003
Posts: 32481
    
214

Can C and D delegate to a common class that does the work?


[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Avtar Khalsa
Greenhorn

Joined: Jul 02, 2008
Posts: 3
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

Joined: Sep 20, 2010
Posts: 3982
    
  18

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.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
 
Have you checked out Aspose?
 
subject: best approach
 
It's not a secret anymore!