投到一个抽象的课......这怎么可能?

use*_*516 4 java inheritance abstract-class

我实际上正在阅读一本关于java中的设计模式的书,我是一个新手:)

http://www.amazon.com/Design-Patterns-Java-TM-Software/dp/0321333020/在关于复合模式的章节我遇到了一个令我困惑的代码,一个抽象类的抽象,我也没有很好理解当子分区调用抽象超类的构造函数时会发生什么,请你帮我!

我正在谈论的演员是在isTree(设置访问过)

        MachineComponent c = (MachineComponent) i.next();
        if (visited.contains(c) || !c.isTree(visited)) 
Run Code Online (Sandbox Code Playgroud)

isTreeisTree超类方法是抽象的时,我怎样才能在转换为抽象超类之后调用子类的方法?

以下是两个类的片段:

package com.oozinoz.machine;
/*
 * Copyright (c) 2001, 2005. Steven J. Metsker.
 */

import java.util.*;
import com.oozinoz.iterator.ComponentIterator;

/**
 * Objects of this class represent either individual machines or composites of
 * machines.
 */

public abstract class MachineComponent {

    /*
     * Subclasses implement this to support the isTree() algorithm.
     */

    protected abstract boolean isTree(Set s);

    // rest of class omitted
}
Run Code Online (Sandbox Code Playgroud)

2:

package com.oozinoz.machine;    
/*
 * Copyright (c) 2001, 2005. Steven J. Metsker.
 */

import java.util.*;
import com.oozinoz.iterator.ComponentIterator;
import com.oozinoz.iterator.CompositeIterator;

 /**
 * Represent a collection of machines: a manufacturing line, a bay, or a
 * factory.
 */

public class MachineComposite extends MachineComponent {
    protected List components = new ArrayList();

    /**
     * @param visited a set of visited nodes
     * @return true if this composite is a tree
     * @see MachineComponent#isTree()
     */

    protected boolean isTree(Set visited) {
        visited.add(this);
        Iterator i = components.iterator();
        while (i.hasNext()) {
            MachineComponent c = (MachineComponent) i.next();
            if (visited.contains(c) || !c.isTree(visited)) 
                return false;
        }
        return true;
    }

    // rest of class omitted
}
Run Code Online (Sandbox Code Playgroud)

wrs*_*der 9

这是运行时类型(实际类型)和编译时类型之间的区别.

抽象类的类型转换MachineComponent很好,因为实际的对象实例实际上是MachineComponent实现所有抽象方法的非抽象子类.

抽象MachineComponent类是指定变量的编译时类型.但是没有用该抽象类创建(或可以)创建实际实例.

  • @ wrscheider99 - 绝对正确.事实上,这是一个抽象类的定义 - 它是一个你不能创建任何具体实例的类 - 你必须在ORDER中创建一个具体的实例.坦率地说,"接口"在Java中往往更有用.但抽象类*在许多情况下都很重要,包括OP的例子. (2认同)