Optional Methods in Java Interface

后端 未结 12 1869
说谎
说谎 2020-11-30 20:53

From my understanding if you implement an interface in java, the methods specified in that interface have to be used by the sub classes implementing the said interface.

12条回答
  •  难免孤独
    2020-11-30 21:38

    If we go through the code of AbstractCollection.java in grepCode which is a ancestor class for all collection implementations, it will help us to understand the meaning of optional methods. Here is the code for add(e) method in AbstractCollection class. add(e) method is optional according to collection interface

    public boolean  add(E e) {
    
            throw new UnsupportedOperationException();
        } 
    

    Optional method means it is already implemented in ancestor classes and it throws UnsupportedOperationException upon invocation. If we want to make our collection modifiable then we should override the optional methods in collection interface.

提交回复
热议问题