首页 > 解决方案 > 为什么扩展抽象类的类中的方法即使没有被调用也会运行?

问题描述

考虑以下:

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. 当我运行代码时,没有调用getor size,打印语句出现在输出中。如何/为什么会发生这种情况?我理解这一点get并且size是必要的,因为AbstractList它是扩展的,但我从不调用sizeor get

一般来说,如果Bextends A,是否会调用一个B固有地调用在 中实现的重写抽象方法的方法B

谢谢

标签: javainheritanceabstract-classextends

解决方案


这就是抽象类/方法的重点:您的基类定义了一组抽象方法和一组非抽象方法B。

现在,最有可能的是,集合B之外的方法将调用来自A 的方法。

换句话说:您使用抽象类来固定某些行为(通过从B存储桶中编写方法),但是为了允许不同的整体行为,您允许用户以不同的方式实现A方法(通过创建不同的子类,以不同的方式实现抽象方法)。


推荐阅读