我正在学习编码,目前我正在尝试通过最后学习类(class)来清理我的大量代码。我告诉你这些只是为了提醒你,我的术语可能仍然不准确:) :)
情况
- 我的代码适用于将在彼此之上绘制的“图层”
- 图层有两种类型:视频图层和图像图层。
- 两种类型的图层都是父类“Layer”的子级
- 它们需要按创建顺序运行
目标
我想为类的每个项目/对象运行代码。
当前代码
import java.util.*;
public class main {
public static void main(String[] args){
// defining the objects
LayerVideo item01 = new LayerVideo();
item01.path = "import/01/";
LayerVideo item02 = new LayerVideo();
item02.path = "import/02/";
LayerImage item03 = new LayerImage();
item03.path = "import/03/";
// here is the main goal:
// to run/call each object from class "Layer"
// "allLayers" does not exist, but that's what I don't know how to do.
allLayers.forEach( item ->{
System.out.println( item.path );
// expected result in console:
// import/01/
// import/02/
// import/03/
});
}
public static class Layer {
}
public static class LayerVideo extends Layer {
public String path;
}
public static class LayerImage extends Layer {
public String path;
}
}
想法
- 如何从类中获取所有切除对象
- 如果我有它们,如何通过变量名称来识别它们?
- 我可以对循环中的对象进行排序/过滤吗?
最佳答案
有两件事:
- 考虑将您的类(class)设为顶级类(class)。因此,不要进入 Main 类的
public static class LayerVideo
内部。如果它们那么重要,那么每个类都应该放入它们自己的 java 文件中。 - 然后了解 Java collections组织对象实例。例如,您可以定义使用 ArrayList。
除此之外,重点可能是:如果您希望两个不同的类有共同的东西,那么您的基类需要拥有它,例如:
public abstract class Layer {
private String path;
public String getPath() { return path; }
public void setPath(String newPath) { path = newPath; }
然后您的子类只需继承该行为即可。
然后,您只需添加将基本类型扩展到集合的对象即可:
List<Layer> layers = new ArrayList<>();
Layer layer = new VideoLayer();
layers.add(layer);
关于Java - for循环类的每个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58504684/