cast an object to an interface in java?

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

    Only the methods in the interface are visible, but all methods in the object may still be invoked, as long as they're made accessible otherwise. For example:

    public interface MyInterface {
        String getName();
    }
    
    public class Obj implements MyInterface {
        private String getFirstName() {
            return "John";
        }
    
        private String getLastName() {
            return "Doe";
        }
    
        @Override
        public String getName() {
            return getFirstName() + " " + getLastName();
        }
    }
    
    public class Sec implements MyInterface {
        private String getDate() {
            return new Date().toString();
        }
    
        @Override
        public String getName() {
            return getDate();
        }
    }
    

    In the above cases, both Obj and Sec can call their private members, even though they will not be visible in other classes. So when you say...

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

    ...as you've asked in the question, while it is true that in myObj and mySec the only method visible is getName(), their underlying implementation can be different.

提交回复
热议问题