Access class variable using Interface type

前端 未结 4 873
爱一瞬间的悲伤
爱一瞬间的悲伤 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 03:46

    No, you can't access the class variable using interface type, but the interface can define method that can access to the variable.

    interface Intrfc {
    
        public String getPickmeUp();
    
    }
    
    
    class MyClass implements Intrfc {
    
        String pickmeUp = "Its Me";
    
        public String getPickmeUp(){
            return pickmeUp;
        }
    
        public static void main(String[] args){
    
            Intrfc ob = new MyClass();
            ob.getPickmeUp();
    
        }
    
    }
    

提交回复
热议问题