Access class variable using Interface type

前端 未结 4 872
爱一瞬间的悲伤
爱一瞬间的悲伤 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();
    
        }
    
    }
    
    0 讨论(0)
  • 2021-01-24 03:55

    If you want to use the method of a class using the object of an interface you can do it as follows:

    //Interface:
    public interface TestOne {  
        int a = 5;
        void test();    
        static void testOne(){      
            System.out.println("Great!!!");
    
        }
    
        default void testTwo(){
    
            System.out.println("Wow!!!");
    
        }
    }
    //-------------------
    //Class implementing it:
    package SP;
    public class TestInterfacesImp implements Test1, TestOne{   
        @Override
        public void test() {
            System.out.println("I Love java");      
        }
    
            public void testM() {
                System.out.println("I Love java too");
            }
    
        public static void main(String[] args) {
            TestOne.testOne();      
            TestOne obj = new TestInterfacesImp();
            obj.testTwo();
            TestInterfacesImp objImp = new TestInterfacesImp();
            objImp.test();
            ((TestInterfacesImp) obj).testM(); //Here casting is done we have casted to class type
    
    
        }
    }
    

    Hope this helps...

    0 讨论(0)
  • 2021-01-24 04:05

    In this definition:

    class MyClass implements Intrfc {
        String pickmeUp = "Its Me";
    }
    

    the field pickmeUp is not even a member of Intrfc interface, so there is no possibility to reach for it using just the interface. pickmeUp is a member of a concrete class - MyClass.

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题