gpt4 book ai didi

java - 线程 "main"java.ClassCastException : MomentOfInertia. 中出现异常 三角形无法转换为 Ix

转载 作者:行者123 更新时间:2023-12-01 12:46:28 24 4
gpt4 key购买 nike

大家。我是Java新手。这是我学习抽象时遇到的问题,实现

可以编译。但是当我输入“java Ass”后,它给出了以下内容:

线程“main”中的异常 java.ClassCastException:MomentOfInertia.triangle 无法转换为 Ix

这是我的代码:

import java.util.Scanner;

class MomentOfInertia
{
interface Ix{public double calcIx(double x, double y);}

interface Iy{public double calcIy();}

interface J{public double calcJ();}

interface I extends Ix, Iy {}

abstract class shape{public abstract void f();}

class triangle extends shape implements I, J
{
public void f(){System.out.println("\n\nAbstract \'shape\'to triangle");}
public double calcIx(double x, double y){return x*y*10;}
//public double calcIy(){return 1;}
//public double calcJ(){return 1;}
}
}

class Ass
{

public static void calc1(Ix a)
{
Scanner scan = new Scanner(System.in);
int input2 = scan.nextInt();
int input3 = scan.nextInt();
System.out.println("\n\t\'interface\' to Ix:" + a.calcIx(input2, input3));
}
//public static void calc2(Iy b){System.out.println("\n\t\'interface\' to Iy:" + b.calcIy());}

public static void main(String[] args)
{
System.out.println("\n\nHere is the demo of polymorphism");

MomentOfInertia MoI = new MomentOfInertia();
MomentOfInertia.triangle t = MoI.new triangle();
calc1((Ix) t);

}
}

最佳答案

这是正常的。您尝试将其实例强制转换为 Ix 的类未实现该接口(interface)。因此,不存在 IS-A 关系,而这种关系是实现此类强制转换所必需的。

class triangle extends shape implements I, J

这意味着,您可以将其转换为:形状、I 和 J,但不能转换为 Ix。

关于java - 线程 "main"java.ClassCastException : MomentOfInertia. 中出现异常 三角形无法转换为 Ix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24655155/

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