使用接口类型访问类变量 [英] Access class variable using Interface type

查看:94
本文介绍了使用接口类型访问类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上课

class MyClass implements Intrfc {

String pickmeUp = "Its Me";

public static void main(String[] args){

Intrfc ob = new MyClass();
ob.pickmeUp;  ---> How can I access this way ?

  }

}

是否可以使用接口类型访问类变量?

Is there any way to access class variable using Interface type ?

推荐答案

是否可以使用接口类型访问类变量?

Is there any way to access class variable using Interface type ?

不.这就是界面的重点.

No. That is the whole point of an interface.

是的,接口只能为您提供行为(方法),而不能为您提供状态"(变量/字段). Java就是这样.

And yes, interfaces only give you behavior (methods), not "state" (variables/fields). That is how things are in Java.

当然,您始终可以使用instanceof检查 actual 对象是否具有某些特定类型,然后 cast 到该类型.但是,正如所说的那样,会破坏使用接口的目的!

Of course, you can always use instanceof to check if the actual object is of some more specific type, to then cast to that type. But as said, that defeats the purpose of using interfaces!

这篇关于使用接口类型访问类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆