gpt4 book ai didi

java - 使用java 8默认方法实现多重继承

转载 作者:行者123 更新时间:2023-11-30 07:37:22 24 4
gpt4 key购买 nike

我想使用 JAVA 8 默认方法作为实现多重继承的手段。因此,我有一个由 addValue() 方法表示的重复代码,我需要将其从实现移至接口(interface)。

interface IX {
ArrayList list = new ArrayList();
default void addValue(Object o) {
this.list.add(o);
}
}

class A implements IX {
//no addValue implementation here
}

class B implements IX {
//no addValue implementation here
}

class Main {
public static void main(String [] args) {
A a = new A();
B b = new B();
a.addValue(this);
b.addValue(this);
}
}

我想知道

  • 如果这是默认方法的有效用法
  • 如果a.addValue(this)语法正确
  • 如果将创建两个不同的列表对象

最佳答案

Java 不允许对状态进行多重继承,只允许对行为进行多重继承。

如果您想共享实例字段的声明,您需要将其放置在抽象类中。

if this is a valid usage of default methods

I use default methods heavily, but since I value immutability, i rarely place methods that mutate state in an interface.

由于(当前)所有接口(interface)方法都是公共(public)的,因此如果我需要继承改变状态的方法,我会将它们(作为 protected )放置在抽象类中。

If the a.addValue(this) syntax is correct

No. Since you are in the static main method there is no "this". What do you want to add to this list?

If two different list objects will be created In your example only one (global) list will be created. It is also important to note that ArrayList is not thread safe and in general should not be used in a global field, CopyOnWriteArrayList (or similar) should be used instead.

下面的例子:

/**
* The Interface IX.
*/
public static interface IX {

/**
* Gets the list.
*
* @return the list
*/
List<Object> getList();

/**
* Adds the value.
*
* @param o the o
*/
default void addValue(Object o) {
this.getList()
.add(o);
}

}

/**
* The Class AbstractIX.
*/
public static abstract class AbstractIx implements IX {

/** The list. */
protected List<Object> list = new ArrayList<>();

@Override
public List<Object> getList() {
return this.list;
}
}

/**
* The Class A.
*/
public static class A extends AbstractIx {
// no addValue implementation here
}

/**
* The Class B.
*/
public static class B extends AbstractIx {
// no addValue implementation here
}

/**
* The Class Main.
*/
public static class Main {

/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
A a = new A();
B b = new B();
a.addValue(1);
a.addValue(2);

b.addValue(1);
System.out.println("List a size should be 2: " + a.getList()
.size());
System.out.println("List b size should be 1: " + b.getList()
.size());
}
}

关于java - 使用java 8默认方法实现多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35198873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com