强制转换为抽象类...这怎么可能? [英] cast to an abstract class...how this is possible?
问题描述
我实际上是在读一本有关Java设计模式的书,我是新手:)
i am actually reading a book about design patterns in java and i am a newbie :)
http://www.amazon.com/Design-Patterns-Java-TM-Software/dp/0321333020/ 在关于复合模式的一章中,我遇到了一个令我困惑的代码,一个抽象类的转换,我也不太了解当子句调用抽象超类的构造函数时会发生什么,请您帮我!
http://www.amazon.com/Design-Patterns-Java-TM-Software/dp/0321333020/ at the chapter about composite pattern i came across a code that puzzles me, a cast to an abstract class, I have also not well understood what happens when the sub-clase calls the constructor of the abstract superclass, can you help me please !!
我正在谈论的演员表位于isTree(访问集)中
the cast that i am talking about is in the isTree( Set visited)
MachineComponent c = (MachineComponent) i.next();
if (visited.contains(c) || !c.isTree(visited))
在将 isTree
后,如何调用子类的 isTree
方法>超类方法是抽象的吗?
How can we call the isTree
method of the subclass after a cast to his abstract superclass
while the isTree
superclass method is abstract?
以下是这两类的摘要:
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
}
推荐答案
这是运行时类型(实际类型)和编译时类型之间的区别。
This is the distinction between runtime type (actual type) and compile-time type.
类型转换为摘要类 MachineComponent
很好,因为实际的对象实例实际上是实现所有功能的 MachineComponent
的一些非抽象子类。抽象方法。
The typecast to an abstract class MachineComponent
is fine, because the actual object instance will actually be some non-abstract subclass of MachineComponent
that implements all of the abstract methods.
抽象的 MachineComponent
类是分配变量的编译时类型。但是,没有(或可以)用该抽象类创建实际实例。
The abstract MachineComponent
class is the compile-time type of the assigned variable. But no actual instance is (or can be) created with that abstract class.
这篇关于强制转换为抽象类...这怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!