具有一些共同属性但没有遗产的两个类

我有两个具有一些共同属性的类:


public class A { 

private String a;

private String b;

private String c;

// setters & getters

}

public class B {

private String a;

private String b;

private String c;

// setters & getters

}

没有租用,我想创建一个可以接受这两个类之一的通用方法


public <T> void myMethod(T object){

object.getC(); // "c" attribute of class A and B

}

我如何在 Java 8 中执行此操作


catspeake
浏览 176回答 3
3回答

慕标5832272

您可以定义这样的接口:interface ISomeInterfaceToGetC {&nbsp; &nbsp; String getC();}实现很简单:class A implements ISomeInterfaceToGetC {&nbsp; &nbsp; @Override&nbsp; &nbsp; public String getC(){&nbsp; &nbsp; &nbsp; &nbsp; return c;&nbsp; &nbsp; }}然后你的两个类都可以实现这个接口,而不是传递T object你可以传递ISomeInterfaceToGetC implementationObject和调用implementationObject.getC();它将返回你的字符串。

www说

为什么不直接使用单独的 POJO 类,它既可以提供通用代码,又不需要继承或实现。class Data{&nbsp; &nbsp; private String a;&nbsp; &nbsp; public String getA(){&nbsp; &nbsp; &nbsp; &nbsp; return this.a;&nbsp; &nbsp; }&nbsp; &nbsp; /* TO DO */}class A {&nbsp; &nbsp;private Data data;&nbsp; &nbsp; /* TO DO */}class B {&nbsp; &nbsp;private Data data;&nbsp; &nbsp; /* TO DO */}public void myMethod(Data data){&nbsp; &nbsp; data.getA();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java