variable of Interface type

后端 未结 3 1626
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 09:01

I am learning Java, I saw the following description regards to interface in a book:

When a variable is declared to be of an interface typ

3条回答
  •  后悔当初
    2021-02-04 09:21

    You cannot instantiate an interface, i.e. you cannot do

    MyInterface foo = new MyInterface(); // Compile-time error.
    

    What you can do is instantiate a class that implements the interface. That is, given a class MyClass

    public class MyClass implements MyInterface {
      // ...
    
      @Override
      void method_one() {
        // ...
      }
      @Override
      int method_two() {
        // ...
      }
    }
    

    you can instantiate it and place a reference to it in your variable like this:

    MyInterface foo = new MyClass();
    

    If you had another class implementing MyInterface

    class MyClass2 implements MyInterface {
      // ...
    }
    

    you can also substitute a reference to this class's instance under your variable:

    MyInterface foo = new MyClass2();
    

    This is where the power of interfaces lies: they define types, not a particular implementation and let you refer to any implementation of a given type.

    It is a very good programming practice to make classes implement interfaces and to use these to refer to instances of these classes. This practice facilitates a great deal of flexibility and reuse.

    Therefore, you should use interface type arguments and variables whenever it is conceivable that different implementations may be passed into the method you're implementing. For example, if you're working with a HashSet instance, you should use a variable of type Set to refer to it (class HashSet implements interface Set).

提交回复
热议问题