gpt4 book ai didi

java - 是否可以将 int 转换为自定义类类型(在 java 中)?如果是那么怎么办?

转载 作者:行者123 更新时间:2023-11-29 08:34:34 25 4
gpt4 key购买 nike

我是 java 初学者,试图创建一个抽象类 Shape 的抽象方法 abstract int area()Shape 类扩展到其他三个类和这些类的覆盖区域方法正在计算面积并返回 int 值,我想存储在 Shape 类数组中。

import java.util.Scanner;
abstract class Shape{
abstract int area();
}

class Ractangle extends Shape {
private int length,width;
public Rectangle(){
System.out.println("Enter length rectangle ");
this.length = Test.scan.nextInt();
System.out.println("Enter width rectangle ");
this.width = Test.scan.nextInt();
}
public int area(){
return length*width;
}
}

class Square extends Shape{
private int side;
public Square(){
System.out.println("Enter side square ");
this.side = Test.scan.nextInt();
}
public int area(){
return side*side;
}
}
class Parlellogram extends Shape{
private int base,height;
public Parallelogram(){
System.out.println("Enter base parallelogram");
this.base = Test.scan.nextInt();
System.out.println("Enter height parallelogram ");
this.height = Test.scan.nextInt();
}
public int area(){
return base*height;
}
}
class Test{
public static Scanner scan;
public static void main(String[] args){
scan = new Scanner(System.in);
Rectangle rect = new Rectangle();
Square sq = new Square();
Parallelogram prlg = new Parallelogram();

Shape[] shapeArray = {rect.area(), sq.area(), prlg.area()}; //error here

//shapeArray[0] = rect.area();
//shapeArray[1] = sq.area();
//shapeArray[2] = prlg.area();
}
}

错误:类型不兼容:无法将 int 转换为 Shape

最佳答案

也许是想写这个?

int[] shapeArray = {ract.area(), sq.area(), prlg.area()};

还是 tihs?

Shape[] shapeArray = {ract, sq, prlg};

如果您计算一个形状的面积,您将不再有一个 Shape,而是一个 int

关于java - 是否可以将 int 转换为自定义类类型(在 java 中)?如果是那么怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com