示例代码如下:
interface ICommonProperty {
int getCommonProperty();
}
class TypeA implements ICommonProperty {
int propertyA;
@Override
public int getCommonProperty() {
return propertyA;
}
}
class TypeB implements ICommonProperty {
int propertyB;
@Override
public int getCommonProperty() {
return propertyB;
}
}
class MyMethod {
public void doSomething(ICommonProperty obj) {
int commonProperty = obj.getCommonProperty();
// use commonProperty here
}
}
在上述示例中,我们定义了一个具有共同属性的接口“ICommonProperty”,并将其实现应用于不同的类型“TypeA”和“TypeB”。然后,我们编写了一个方法“doSomething”,该方法仅接受实现“ICommonProperty”的对象,并使用“getCommonProperty”方法获取共同属性。这样,无论传递给“doSomething”方法的是“TypeA”还是“TypeB”,都可以获取到其共同属性,并进行相应的操作。