Ошибка: метод add(Shape) в типе ArrayList неприменим для аргументов (Shape.Rectangle).JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка: метод add(Shape) в типе ArrayList неприменим для аргументов (Shape.Rectangle).

Сообщение Anonymous »

Я пытаюсь добавить новую фигуру в ArrayList, но получаю сообщение об ошибке: Метод add(Shape) в типе ArrayList неприменим для аргументов (Shape.Rectangle)
Shape.Rectangle — это созданный мной собственный класс. Аргументами для него являются Rectangle (имя строки, двойная длина, двойная ширина).
Я получаю эту ошибку также для круга и треугольника.
Если я изменю тип ArrayList на Object вместо Shape, метод create() сработает. Однако метод display() перестает работать.
Мой код приведен ниже:
public static void create(ArrayList list) throws FileNotFoundException {
// Create shape objects using data from an input file
File dataFile = new File("./src/shape/dataFile.txt");
Scanner scan = new Scanner(dataFile);

while (scan.hasNextLine()) {
String shapeType = scan.nextLine();
if (shapeType.equals("Rectangle")) {
list.add(new Rectangle(scan.nextLine(), scan.nextDouble(), scan.nextDouble()));
}
else if (shapeType.equals("Circle")) {
list.add(new Circle(scan.nextLine(), scan.nextDouble()));
}
else if (shapeType.equals("Triangle")) {
list.add( new Triangle(scan.nextLine(), scan.nextDouble(), scan.nextDouble(), scan.nextDouble()));
}

}
scan.close();
}

public static void display(ArrayList list) {

for (int i = 0; i < list.size(); i++) {
Shape shape = list.get(i);
String name = shape.getName();
Double area = shape.area();

System.out.println(name);
System.out.println(area);
}
}

Если я изменю тип ArrayList на Object вместо Shape, метод create() сработает. Однако я получаю ошибки в методе display() при попытке получитьName() и area().
Изменить:
Код для Shape и Rectangle:
abstract class Shape {

/**
* The name of this shape
*/
private String name;

/**
* Default constructor
* Creates a Shape instance with a default name such as "Shape"
*/
public Shape() {
this.name = "Shape";
}

/**
* Second constructor
* Given a name, creates a Shape instance with the name
* @param name Name of the new shape
*/
public Shape(String name) {
this.name = name;
}

/**
* Retrieves the name of this shape
* @return Returns the name of shape
*/
public String getName() {
return name;
}

/**
* Given a name, changes the name of this shape to the new name
* @param newName New name of the shape
*/
public void setName(String newName) {
this.name = newName;
}

/**
* Returns the area of this shape
* @return Return of the area of shape
*/
abstract double area();

/**
* Compares this with some other object
* This method overrides the java equals method
* @param obj A reference to some other object
* @return true if some other object is equal to this shape, false otherwise
*/
public boolean equals(Object obj) {
if(obj == this.name) {
return true;
}
else {
return false;
}
}

/**
* Represents this shape as a string literal
* This method overrides the Java toString method
* @return A string representation of the shape
*/
public String toString() {
return this.getClass().getSimpleName() + ": " + this.name;
}

/**
* Rectangle Subclass
*/
public static class Rectangle {

/**
* Instance variables
* Name, length, and width of shape.
*/
private String name;
private Double length, width;

/**
* Default Constructor
* Creates a default rectangle instance.
*/
public Rectangle() {
this.name = "Rectangle";
this.length = 1.0;
this.width = 1.0;
}

/**
* Second Constructor
* Given a name, a length, and a width, creates a rectangle instance with the name, the length, and the width.
* @param name, length, width Create a rectangle with these arguements
*/
public Rectangle(String name, Double length, Double width) {
this.name = name;
this.length = length;
this.width = width;
}

/**
* getName
* Returns the name of this rectangle
* @return name Return name of this rectangle
*/
public String getName() {
return name;
}

/**
* setName
* Given a name, replace the name of this rectangle
* @param newName Name to replace the original name of this rectangle
*/
public void setName(String newName) {
this.name = newName;
}

/**
* getLength
* Returns the length of this rectangle
* @return length
*/
public Double getLength() {
return length;
}

/**
* setLength
* Given a length, changes the length of this rectangle to the new length.
* @param newLength
*/
public void setLength(Double newLength) {
this.length = newLength;
}

/**
* getWidth
* Returns the width of this rectangle
* @Return width
*/
public Double getWidth() {
return width;
}

/**
* setWidth
* Given a width, changes the width of this rectangle to the new width
* @param newWidth
*/
public void setWidth(Double newWidth) {
this.width = newWidth;
}

/**
* Area
* Returns the area of this rectangle
* @return area
*/
public Double area() {
double area = this.length * this.width;
return area;
}

/**
* Equals
* Compares this rectangle with some other object.
* @param obj Reference object to compare to
* @return true if some other object is equal to this rectangle, false otherwise
*/
public boolean equals(Object obj) {

if(obj == this.name) {
return true;
}
else {
return false;
}
}

/**
* toString
* Represents this rectangle as a string literal.
* @return A string representation of this rectangle
*/
public String toString() {
return this.getClass().getSimpleName() + ": " + this.name;
}
}


Подробнее здесь: https://stackoverflow.com/questions/783 ... icable-for
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»