File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30506
    
150

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


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, 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: 3646
    
  16

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: best approach