cast an object to an interface in java?

后端 未结 8 1712
半阙折子戏
半阙折子戏 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:27

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

    For this to be legal, both Obj and Sec will have to be implementers of MyInterface. The difference between these two objects would be how they provide that implementation. Obj and Sec could do two very different or very similar things, but their commonality is that they would adhere to a contract that you could rely upon. Consider you have a method

    public void doSomethingWith(MyInterface thing) {
         thing.frob();
    }
    

    Each object, myObj and mySec, could be passed into this method, and this method could then use that object's frob method (assuming frob is part of the interface declaration). This is liberating. This allows you to do very powerful things, by programming to interfaces and not to implementations. For example, you can extend functionality of classes and not change a line of code in those classes, you simply pass a different implementation of a dependency. You are not tied to, or coupled with, any one implentation inside the method doSomethingWith.

    but i also read that if we declare the object myObj as MyInterface, myObj won't be able to use its own methods (from the class Obj), is that correct

    Internally, instances of Obj will continue to have full access to the Obj API. myObj is still an Obj, it will always be able to use its own implementation details.

    public interface MyInterface {
        void frob();
    }
    
    public class Obj implements MyInterface {
    
        public void frob() {
            doFrobbing();
        }
    
        private void doFrobbing() {
            System.out.println("frobbing");
        }
    
        public static void main(String[] args) {
            MyInterface myObj = new Obj();
            myObj.frob(); // still internally calls doFrobbing()
            ((Obj)myObj).doFrobbing(); // visible only via class reference
        }
    }
    

    Instances of Obj will still be instances of Obj, and those instances will still be able to use doFrobbing. Externally, persons using those instances via the interface reference will only be able to access the interface methods.

提交回复
热议问题