java()中的多个inhetitance和受保护的变量

时间:2017-04-13 08:09:10

标签: java interface multiple-inheritance

正如我们在Java中所知,我们在接口中不能有多个继承和受保护的变量,那么我该如何实现这个代码呢?

Bar.java

public class Bar {
    protected int  a = 0;
    public void increaseA() {
        a++;
    }
    public void printA() {
        System.out.println(a);
    }
}

Foo.java

public class Foo extends Bar, FooBar {
    @Override
    public void printClassName() {
        printClassName();
        System.out.println("Foo");
    }
}

FooBar.java

public class FooBar {
    void printClassName(){
        System.out.println("FooBar");
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Foo foo = new Foo();
        FooBar fooBar = foo;
        foo.printClassName();
        Bar bar = foo;
        bar.increaseA();
        bar.printA();
    }
}

2 个答案:

答案 0 :(得分:2)

为此目的尝试使用组合(这里我们得到了Mediator模式)

  public interface BarInterface {
    void increaseA();

    void printA();
  }

  public interface FooBarInterface {
    void printClassName();
  }

  public class FooBar implements FooBarInterface {
    @Override
    public void printClassName() {
      System.out.println("FooBar");
    }
  }

  public class Bar implements BarInterface {
    protected int a = 0;

    public void increaseA() {
      a++;
    }

    public void printA() {
      System.out.println(a);
    }
  }

  public class Foo implements BarInterface, FooBarInterface {

    private final BarInterface bar;
    private final FooBarInterface fooBar;

    public Foo(Bar bar, FooBar fooBar) {
      this.bar = bar;
      this.fooBar = fooBar;
    }

    @Override
    public void printClassName() {
      fooBar.printClassName();
    }

    @Override
    public void increaseA() {
      bar.increaseA();
    }

    @Override
    public void printA() {
      bar.printA();
    }
  }

答案 1 :(得分:0)

abstract class Bar {
    protected  int  a = 0;
    public  void increaseA() {
        a++;
    }
    public void printA() {
        System.out.println(a);
    }


}

interface FooBar {
    default void printClassName(){
        System.out.println("FooBar");
    }
}

class Foo extends Bar implements FooBar {
    @Override
    public void printClassName() {
        FooBar.super.printClassName();
        System.out.println("Foo");
    }
}



public class Q4 {
    public static void main(String[] args) {
        Foo foo = new Foo();
        FooBar fooBar = foo;
        foo.printClassName();
        Bar bar = foo;
        bar.increaseA();
        bar.printA();
    }
}

所以输出是

  

FooBar的

     

     

1