实现类的访问实例变量

时间:2018-08-13 15:46:45

标签: java interface

该接口我有一个this.dataService.addData(this.newData).subscribe((ev:HttpEvent<any>)=>{ console.log("add data - response is ",ev); if(ev.type === HttpEventType.Response) { console.log('response from server: returning body '+ev.body); let isResponseStructureOK: boolean = this.helper.validateServerResponseStructure(ev.body); if (isResponseStructureOK) { let response:ServerResponseAPI = ev.body; console.log("received response from server: " + response.result); let dialogComponentRef: ComponentRef<DialogBoxComponent> = this.maxFilesDialogContainerRef.createComponent(this.dialogFactory); dialogComponentRef.instance.dialogMessage = response.result + ": " + response['additional-info']; dialogComponentRef.instance.dialogID = "maxFilesDialog"; //TODOM - once this view gets added, I am not deleting it from the viewcontainer once the dialog's OK is pressed. Need to find a way to do this. dialogComponentRef.instance.dialogShow(); } else { console.log("received incorrect response structure from server: ", ev.body); let dialogComponentRef: ComponentRef<DialogBoxComponent> = this.maxFilesDialogContainerRef.createComponent(this.dialogFactory); dialogComponentRef.instance.dialogMessage = "Server error"; dialogComponentRef.instance.dialogID = "maxFilesDialog"; //TODOM - once this view gets added, I am not deleting it from the viewcontainer once the dialog's OK is pressed. Need to find a way to do this. dialogComponentRef.instance.dialogShow(); } } else { console.log("not response. ignoring"); } }); 和一个interface A。这是旧版代码,现在我尝试从impl类implementation class B返回另一个变量,而不更改方法签名。我在B类中创建了一个B。访问它的最佳方法是什么?我应该添加一个公共的getter函数来通过接口A还是直接在instance variable中调用getter?

示例代码:

B

public interface A{ } public class B implements A{ private int a =100; public int getA { return a; } } 类访问a的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

如果它仅特定于类B,并且不会被实现接口A的任何其他类使用,则应将其限制为类B,否则,如果它是所有实现A的通用用例,则您应该将访问器添加到接口A。

答案 1 :(得分:0)

这取决于您的情况。

如果B的变量是通用的(很少)与接口A相关联,则可以在接口A中创建一个getter方法。诸如SQL驱动程序接口中的Connection,{{ 1}}界面

在几乎其他情况下,实现B的变量仅特定于该实现,因此您应从B实例访问它。