簡體   English   中英

為什么擴展Abstract類的類中的方法即使未調用也仍在運行?

[英]Why are methods in class that extends Abstract class running even when not called?

考慮以下:

public class OuterClass {
    static class NestedClass extends AbstractList<List<Integer>> {
        void add(/* parameters here */) {
            // note this method is not declared public
            // print here does NOT appear in output
            // implementation details here
        }

        public int size() {
            // print here appears in output
            // implementation details here
        }

        public List<Integer> get(int index) {
            // print here appears in output
            // implementation details here            
        }
    }

     public static List<List<Integer>> method(/* parameters here */) {
         NestedClass nc = new NestedClass();
         nc.add(..);
     }
}

然后在一個單獨的方法中,創建一個NestedClass實例。 當我運行代碼時,從未調用過getsize ,打印語句出現在輸出中。 這是怎么/為什么發生的? 我知道getsize是必需的,因為AbstractList被擴展了,但是我從不調用sizeget

一般來說,如果B延伸A ,將到的方法的任何呼叫B固有調用中實現的重寫的抽象方法B

謝謝

即抽象類/方法整點:您的基類定義的抽象方法的一組A,和非抽象方法的一組B中

現在,最有可能B之外的方法將是從A調用的方法。

換句話說:您使用抽象類來固定某些行為(通過將方法寫出B桶),但是為了允許不同的總體行為,您允許用戶以不同的方式實現A方法(通過創建不同的子類) ,則以不同的方式實現抽象方法)。

AbstractList中的方法public boolean add(E e)具有實現調用add(size(), e)

還有方法public Iterator<E> iterator()依賴於后備列表的size()get(int)remove(int)方法。

這是依賴get(int)的方法的列表:

  • 指數
  • lastIndexOf
  • 迭代器
  • 的ListIterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM