cast an object to an interface in java?

后端 未结 8 1695
半阙折子戏
半阙折子戏 2021-02-01 23:36

if we cast an object to an interface, won\'t this object be able to call its own methods? in the following example, myObj will only be able to call MyInterface meth

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-02 00:28

    MyInterface myObj = new Obj();
    MyInterface mySec = new Sec();
    

    You declare an instance of a MyInterface named myObj. You initialize it with new Obj(); which is authorized by the compiler if Obj implements MyInterface. myObj can only call MyInterface methods obviously. Same for the second line.

    Here is a sample code to try:

    public class Test {
    
        public static void main(String args[]){
              A a = new A();
              a.say();
              a.a();
    
              B b = new B();
              b.say();
              b.b();
    
              I ia = new A();
              ia.say();
              ia.a(); // fail
        }
    
    }
    
    interface i {
        public void say();
    }
    
    class A implements i {
        public void say(){
            System.out.println("class A");
        }
        public void a(){
            System.out.println("method a");
        }
    }
    
    class B implements i {
        public void say(){
            System.out.println("class B");
        }
        public void b(){
            System.out.println("method b");
        }
    }
    

提交回复
热议问题