Access class variable using Interface type

前端 未结 4 913
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 03:39

I\'ve following class

class MyClass implements Intrfc {

String pickmeUp = \"Its Me\";

public static void main(String[] args){

Intrfc ob = new MyClass();
ob.pi         


        
4条回答
  •  渐次进展
    2021-01-24 04:07

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

    No. That is the whole point of an interface.

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

    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!

提交回复
热议问题