Creating object with reference to Interface

后端 未结 6 953
自闭症患者
自闭症患者 2021-02-04 22:08

A reference variable can be declared as a class type or an interface type.If the variable is declared as an interface type, it can reference any object of any class that impleme

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 22:57

    But in my code is displaying displayName()method undefined.

    Right, because displayName is not defined in the Printable interface. You can only access the methods defined on the interface through a variable declared as having that interface, even if the concrete class has additional methods. That's why you can call sysout, but not displayName.

    The reason for this is more apparent if you consider an example like this:

    class Bar {
        public static void foo(Printable p) {
            p.sysout();
            p.displayName();
        }
    }
    
    class Test {
        public static final void main(String[] args) {
            Bar.foo(new Parent());
        }
    }
    

    The code in foo must not rely on anything other than what is featured in the Printable interface, as we have no idea at compile-time what the concrete class may be.

    The point of interfaces is to define the characteristics that are available to the code using only an interface reference, without regard to the concrete class being used.

提交回复
热议问题