Why can't we instantiate an abstract class in Java?

前端 未结 16 1019
挽巷
挽巷 2020-12-08 05:36

I understand:

  1. Since an abstract class is nothing on its own, e.g. vehicle, we want to create an object of an concrete implementation, like Car, Bike, etc.
16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 05:59

    Well actually you can - but only if you implement any methods that have been declared abstract or left out.

    /**
     * A classic adaptor pattern.
     *
     * @param 

    * @param */ public static interface Adapter { public Q adapt(P p); } /** * An I walks an iterator of one type but delivers items of a different type. * * Please fill in the `next()` method. Use an Adaptor for convenience. * * @param * @param */ public abstract static class I implements Iterator { protected final Iterator it; public I(Iterator it) { this.it = it; } @Override public boolean hasNext() { return it.hasNext(); } @Override public void remove() { it.remove(); } } /** * Use an adaptor to transform one type into another. * * @param * @param */ public static class IA extends I { private final Adapter adaptor; public IA(Iterator it, Adapter adaptor) { super(it); this.adaptor = adaptor; } @Override public T next() { // Implement the abstract method on-the-fly. return adaptor.adapt(it.next()); } }

    Added

    The IA class instantiates an object of the I abstract class and implements the next method that was missing from the I class. You are actually creating an object of an anonymous that implements the implied abstract method.

提交回复
热议问题