所以可以说我有以下代码。
public class ImageMaker {
// Variables
static ArrayList<Shape> shapes = new ArrayList<Shape>();//all the shapes contained in the image
public static void main (String[] args) {
shapes.add(new Rect()); //here i want to add an object Rect
}
}
并显示在另一个名为Shape的类中,如下所示。现在,我想将Rect类型的对象添加到我的形状数组列表中,但是我不能,因为它说Rect无法解析为类型。我该如何执行呢?当然,我有更多的实例变量和方法,但没有显示。让我知道您是否需要更多信息来回答。谢谢!
public class Shape {
public class Rect extends Shape {
//rect instance variables
public Rect(){
super();
System.out.print("Youve made a rect within shape");
}
}
正如@tsnorri在评论中提到的那样,您只需要声明一个Rect
类即可Shape
。
public class Shape {
}
public class Rect extends Shape {
//rect instance variables
public Rect(){
super();
System.out.print("Youve made a rect within shape");
}
}
如果您想了解有关Java中嵌套类的更多信息,这是一个很好的起点:http : //docs.oracle.com/javase/tutorial/java/javaOO/nested.html
编辑(工作示例)
通常,我建议您阅读一些有关OO编程和JAVA的基础知识。
这是将Shape
和都添加Rect
到的工作示例ArrayList
。
import java.util.ArrayList;
class ImageMaker
{
static ArrayList<Shape> shapes = new ArrayList<Shape>();//all the shapes contained in the image
public static void main(String args[])
{
shapes.add(new Shape());
shapes.add(new Rect());
}
public static class Shape {
System.out.print("Created new Shape");
}
public static class Rect extends Shape {
//rect instance variables
public Rect(){
super();
System.out.print("You've made a rect within shape");
}
}
}
干杯
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句