Access class variable using Interface type

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

提交回复
热议问题