First of all... Sorry for this post. I know that there are many many posts on stackoverflow which are discussing multiple inheritance. But I already know that Java does not
Using composition would be the way to go as another developer suggested. The main argument against multiple inheritance is the ambiguity created when you're extending from two classes with the same method declaration (same method name & parameters). Personally, however, I think that's a load of crap. A compilation error could easily be thrown in this situation, which wouldn't be much different from defining multiple methods of the same name in a single class. Something like the following code snippet could easily solve this dilema:
public MyExtendedClass extends ClassA, ClassB {
public duplicateMethodName() {
return ClassA.duplicateMethodName();
}
}
Another argument against multiple inheritance is that Java was trying to keep things simple so that amateur developers don't create a web of interdependent classes that could create a messy, confusing software system. But as you see in your case, it also complicates and confuses things when it's not available. Plus, that argument could be used for a 100 other things in coding, which is why development teams have code reviews, style checking software, and nightly builds.
In your particular situation though, you'll have to settle with composition (see Shojaei Baghini's answer). It adds a bit of boiler plate code, but it emulates the same behavior as multiple inheritance.
I run in a similar problem on Android. I needed to extend a Button and a TextView (both inheriting from View) with additional functions. Due to not having access to their super class, I needed to find another solution. I´ve written a new class which encapsulates all the implementations:
class YourButton extends Button implements YourFunctionSet {
private Modifier modifier;
public YourButton(Context context) {
super(context);
modifier = new Modifier(this);
}
public YourButton(Context context, AttributeSet attrs) {
super(context, attrs);
modifier = new Modifier(this);
}
public YourButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
modifier = new Modifier(this);
}
@Override
public void generateRandomBackgroundColor() {
modifier.generateRandomBackgroundColor();
}
}
class Modifier implements YourFunctionSet {
private View view;
public Modifier(View view) {
this.view = view;
}
@Override
public void generateRandomBackgroundColor() {
/**
* Your shared code
*
* ......
*
* view.setBackgroundColor(randomColor);
*/
}
}
interface YourFunctionSet {
void generateRandomBackgroundColor();
}
The problem here is, your classes need the same super class. You can also try to use different classes, but check which type it is from, for example
public class Modifier{
private View view;
private AnotherClass anotherClass;
public Modifier(Object object) {
if (object instanceof View) {
this.view = (View) object;
} else if (object instanceof AnotherClass) {
this.anotherClass = (AnotherClass) object;
}
}
public void generateRandomBackgroundColor(){
if(view!=null){
//...do
}else if(anotherClass!=null){
//...do
}
}
}
So here is basically my Modifier class the class which encapsulates all implementations.
Hope this helps someone.
Actually, I have no good answer other than Java SHOULD have Multiple Inheritance. The whole point that interfaces should be able to replace the need for Multiple Inheritance is like the big lie that when repeated enough times becomes true.
The argument is that Multiple Inheritance causes all these problems (la-di-dah), yet I keep hearing those arguments from Java developers who have never used C++. I also don't EVER remember C++ programmers saying "Gee, I love C++, but if they would only get rid of Multiple Inheritance, it would become a great language". People used it when it was practical and didn't when it wasn't.
Your problem is a classic case of where Multiple Inheritance would be appropriate. Any suggestion to refactor the code is really telling you how to work around the PROBLEM that Java has no Multiple Inheritance.
Also all the discussion that "oh, delegation is better, la-di-dah" is confusing religion with design. There is no right way. Things are either more useful or less useful and that is all.
In your case Multiple Inheritance would be more useful and a more elegant solution.
As far as refactoring your code into a less useful form to satisfy all the religious people who have never used Multiple Inheritance and believe "Multiple Inheritance is bad", I guess you will have to downgrade your code because I don't see Java "improving" in that way any time soon. There are too many people repeating the religious mantra to the point of stupidity that I can't see it ever being added to the language.
Actually, my solution for you would be "x extends Tagged, XMLElement" and that would be all.
...but as you can see from the solutions provided above, most people think that such a solution would be WAY TOO COMPLEX AND CONFUSING!
I would prefer to venture into the "x extends a,b" territory myself, even if it is a very frightening solution that might overwhelm the abilities of most Java programmers.
What is even more amazing about the solutions suggested above is that everyone here who suggested that you refactor your code into "delegation" because Multiple Inheritance is bad, would, if they were confronted with the very same problem, would solve the problem by simply doing: "x extends a,b" and be done with it, and all their religious arguments about "delegation vs inheritance" would disappear. The whole debate is stupid, and it only being advanced by clueless programmers who only demonstrate how well they can recite out of a book and how little they can think for themselves.
You are 100% correct that Multiple Inheritance would help, and no, you are doing anything wrong in your code if you think Java should have it.
First it makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think).
How about using aggregation for the tags?
Rename your Tagged
class to Tags
.
Create a Tagged
interface:
interface Tagged { Tags getTags(); }
Let each class that needs to be "tagged", implement Tagged
and let it have a tags
field, which is returned from getTags
.
Second I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.
That's right, interfaces can't have instance variables. The data structures storing the tags however, shouldn't necessarily IMO be part of the classes that are tagged. Factor out the tags in a separate data structure.
Just wondering if one could not simply use inner (member) classes (LRM 5.3.7)? E.g. like this (based on the first answer above):
// original classes:
public class Tagged {
// ...
}
public class XMLElement {
// ...
}
public class TaggedXmlElement {
public/protected/private (static?) class InnerTagged extends Tagged {
// ...
}
public/protected/private (static?) class InnerXmlElement extends XMLElement {
// ...
}
}
This way you have a class TaggedXmlElement which actually contains all elements from the two original classes and within TaggedXmlElement you have access to non-private members of the member classes. Of course one would not use "super", but call member class methods. Alternatively one could extend one of the classes and make the other a member class. There are some restrictions, but I think they can all be worked around.
I'd solve it that way: extract interfaces for the Tagged
and XMLElement
class (maybe you don't need all methods in the public interface). Then, implement both interfaces and the implementing class has a Tagged
(your actual concrete Tagged
class) and an XMLElement
(your actual concrete XMLElement
class):
public class MyClass implements Tagged, XMLElement {
private Tagged tagged;
private XMLElement xmlElement;
public MyClass(/*...*/) {
tagged = new TaggedImpl();
xmlElement = new XMLElementImpl();
}
@Override
public void someTaggedMethod() {
tagged.someTaggedMethod();
}
}
public class TaggedImpl implements Tagged {
@Override
public void someTaggedMethod() {
// so what has to be done
}
}
public interface Tagged {
public void someTaggedMethod();
}
(and the same for XMLElement)