How can interfaces replace the need for multiple inheritance when have existing classes

后端 未结 10 1014
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 00:48

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

10条回答
  •  余生分开走
    2020-11-29 01:06

    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.

提交回复
热议问题