Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting from two Java classes

I know Java forbids inheriting from multiple classes and allows implementing any number of interfaces. However, while interfaces are good for polymorphism, they cannot contain any actual code that their subclasses may want to share. What if I have two different superclasses that have shared code that I want to use in my subclass?

Example: In my program, there are two superclasses, one that works with HashMaps and one that works with Strings, and both have direct subclasses, and all is fine there. But now I have a third that requires the shared functions of both superclasses, but it can only extend one. Is there an easy way to redesign this class structure without having to duplicate a lot of code?

like image 849
donnyton Avatar asked Jul 01 '26 19:07

donnyton


2 Answers

Use delegation rather than inheritance:

public class Third implements FirstInterface, SecondInterface {
    private First first;
    private Second second;

    public void foo() {
        first.foo();
    }

    public String bar() {
        return second.bar();
    }
}
like image 69
JB Nizet Avatar answered Jul 03 '26 08:07

JB Nizet


I've seen this done by

  1. Extracting an interface from both of the superclasses
  2. Creating a class that implements the interfaces, then delegating all calls to the actual objects

    public interface IFirst { public void foo(); }
    
    public interface ISecond { public void bar(); }
    
    public class Third implements IFirst, ISecond {
        private IFirst first;
        private ISecond second;
    
        public Third(IFirst first, ISecond second) {
            this.first = first;
            this.second = second;
        }
    
        @Override
        public void foo() {
            first.foo();
        }
        @Override
        public String bar() {
            return second.bar();
        }
    }
    

This will not give you access to the protected members in the class heirarchy. If that is what you are looking for, you're out of luck in Java. However, this will allow you to refer to this object as both IFirst and ISecond using polymorphically. Thus, you'll be able to access it in external code that requires either one of the two types.

Note: I stole the naming from JB.

like image 30
Ryan Gross Avatar answered Jul 03 '26 08:07

Ryan Gross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!