java转换为抽象类。。。这怎么可能?
我正在读一本关于java设计模式的书,我是一个新手:)
http://www.amazon.com/Design-Patterns-Java-TM-Software/dp/0321333020/在关于复合模式的章节中,我遇到了一个让我困惑的代码,一个对抽象类的转换,我也不太理解子类调用抽象超类的构造函数时会发生什么,你能帮我吗
我所说的演员阵容在iTree(场景)
MachineComponent c = (MachineComponent) i.next();
if (visited.contains(c) || !c.isTree(visited))
当isTree
超类方法是抽象的时,我们如何在对其抽象超类进行转换后调用子类的isTree
方法
以下是这两个类的片段:
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
}
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
}
# 1 楼答案
isTree只是抽象类的抽象。一旦类被初始化为非抽象类,将其转换为抽象类不会改变其内存。因此,在抽象类上调用该方法可以有效地在具体实现上调用它
它之所以有用,是因为它通过抽象实现传递子类
假设字符串类有“length”方法。没有必要为每个可能的字符串类型子类都提供一个函数。相反,您可以将其转换为具有“length”实现的基本(抽象)字符串,并将其传递给其他人
# 2 楼答案
好吧,让我们来看一下
Cat
,它是抽象类Animal
的一个子类你可以把
Cat
转换成Animal
,因为猫是动物。它做正常动物所做的一切,因为它具有动物的功能子类化抽象类也是一样的。你可以简单地使用“is a”,因为它是一个子类
你可以将动物列表定义为动物园,但它可以有狗和猫——毕竟,它们都是动物
将一个
Cat
转换成一个Animal
实际上并不会使它变得比以前更像一个Cat
——你只需要告诉你的代码对待它就像对待任何其他动物一样编辑
如果你不喜欢猫(我也不喜欢),让我把你转到Wikipedia article about inheritance。如果不能强制转换抽象类,那么它们将毫无用处