Can one class extend two classes?

JavaAndroidMultiple Inheritance

Java Problem Overview


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:

  1. BillingInterface

    public interface BillingInterface extends PreferenceActivity, AbstractBillingActivity {
    
    }
    
  2. PreferenceActivity

    public interface PreferenceActivity {
    
    }
    
  3. AbstractBillingActivity

    public interface AbstractBillingActivity {
        
        	void onCreate(Bundle savedInstanceState);
        
    }
    

and then

public class Preferences implements BillingInterface {

Java Solutions


Solution 1 - Java

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 a PreferenceActivity and an AbstractBillingActivity?

Solution 2 - Java

Java doesn't support multiple inheritance. You can implement multiple interfaces, but not extend multiple classes.

Solution 3 - Java

Another solution is to create a private inner class that extends the second class. e.g a class that extends JMenuItem and AbstractAction:

public class MyClass extends JMenuItem {


    private class MyAction extends AbstractAction {
        // This class can access everything from its parent...
    }

}

Solution 4 - Java

Java 1.8 (as well as Groovy and Scala) has a thing called "Interface Defender Methods", which are interfaces with pre-defined default method bodies. By implementing multiple interfaces that use defender methods, you could effectively, in a way, extend the behavior of two interface objects.

Also, in Groovy, using the @Delegate annotation, you can extend behavior of two or more classes (with caveats when those classes contain methods of the same name). This code proves it:

class Photo {
    int width
    int height
}    
class Selection {
    @Delegate Photo photo    
    String title
    String caption
}    
def photo = new Photo(width: 640, height: 480)
def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo)
assert selection.title == "Groovy"
assert selection.caption == "Groovy"    
assert selection.width == 640
assert selection.height == 480

Solution 5 - Java

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.

Solution 6 - Java

Java does not support multiple inheritance. However, your problem may be solved using interfaces.

The easiest solution would be to create an interface for AbstractBillingActivity and PreferenceActivityand implement them both.

Solution 7 - 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.

Solution 8 - Java

Familiar with multilevel hierarchy?

You can use subclass as superclass to your another class.

You can try this.

public class PreferenceActivity extends AbstractBillingActivity {}

then

public class Preferences extends PreferenceActivity {}

In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.

Solution 9 - Java

Java does not support multiple inheritance, that's why you can't extend a class from two different classes at the same time.

Rather, use a single class to extend from, and use interfaces to include additional functionality.

Solution 10 - Java

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/

Solution 11 - Java

Also, instead of inner classes, you can use your 2 or more classes as fields.

For example:

Class Man{
private Phone ownPhone;
private DeviceInfo info;
//sets; gets
}
Class Phone{
private String phoneType;
private Long phoneNumber;
//sets; gets
}

Class DeviceInfo{

String phoneModel;
String cellPhoneOs;
String osVersion;
String phoneRam;
//sets; gets
}

So, here you have a man who can have some Phone with its number and type, also you have DeviceInfo for that Phone.

Also, it's possible is better to use DeviceInfo as a field into Phone class, like

class Phone {
DeviceInfo info;
String phoneNumber;
String phoneType;
//sets; gets
}

Solution 12 - Java

If you are interested in using methods from multiple classes, the best way to approach to it is to use Composition instead of Inheritence

Solution 13 - Java

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:

trait EmployeeTrait {
    int getId() {
         return 1000 //Default value
    }
    abstract String getName() //Required
}

trait CustomerTrait {
    String getCompany() {
        return "Internal" // Default value
    }
    abstract String getAddress()
}

class InternalCustomer implements EmployeeTrait, CustomerTrait {
    String getName() { ... }
    String getAddress() { ... }
}

def internalCustomer = new InternalCustomer()
println internalCustomer.id // 1000
println internalCustomer.company //Internal

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLA_View Question on Stackoverflow
Solution 1 - JavaEtienne de MartelView Answer on Stackoverflow
Solution 2 - JavaMatView Answer on Stackoverflow
Solution 3 - JavaJonny RimkusView Answer on Stackoverflow
Solution 4 - JavadjangofanView Answer on Stackoverflow
Solution 5 - JavaJulesView Answer on Stackoverflow
Solution 6 - JavanejckorasaView Answer on Stackoverflow
Solution 7 - JavaPaul SonierView Answer on Stackoverflow
Solution 8 - JavaAyukNayrView Answer on Stackoverflow
Solution 9 - JavaMD Sayem AhmedView Answer on Stackoverflow
Solution 10 - JavaCrazySynthaxView Answer on Stackoverflow
Solution 11 - JavaDredView Answer on Stackoverflow
Solution 12 - JavaSanthoshView Answer on Stackoverflow
Solution 13 - JavalepeView Answer on Stackoverflow