My class should extend two classes at the same time:
public class Preferences extends AbstractBillingActivity {
public class Preferences extends PreferenceActivity {
How to do so?
Upd. Since this is not possible, how should I use that AbstractBillingActivity with Preferences then?
Upd2. If I go with interfaces, should I create:
BillingInterface
public interface BillingInterface extends PreferenceActivity, AbstractBillingActivity { }
PreferenceActivity
public interface PreferenceActivity { }
AbstractBillingActivity
public interface AbstractBillingActivity { void onCreate(Bundle savedInstanceState); }
and then
public class Preferences implements BillingInterface {
No you cannot make a class extend to two classes.
A possible solution is to make it extend from another class, and make that class extend from another again.
Java does not support multiple inheritance.
There are a few workarounds I can think of:
The first is aggregation: make a class that takes those two activities as fields.
The second is to use interfaces.
The third is to rethink your design: does it make sense for a
Preferences
class to be both aPreferenceActivity
and anAbstractBillingActivity
?Familiar with multilevel hierarchy?
You can use subclass as superclass to your another class.
You can try this.
then
In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.
I can think of a workaround that can help if the classes you want to extend include only methods.
Write these classes as interfaces. In Java, you can implements any number of interfaces, and implement the methods as default methods in the interfaces.
https://www.geeksforgeeks.org/default-methods-java/
What you're asking about is multiple inheritance, and it's very problematic for a number of reasons. Multiple inheritance was specifically avoided in Java; the choice was made to support multiple interface implementation, instead, which is the appropriate workaround.
In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:
Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won't be able to nicely implement inheritance (for example, you can't use protected methods in traits). Follow the accepted answer's recommendation if possible.