我试图为我的任务创建一个二维形状。为此,我将首先创建一个抽象的 Shape2d类。我的分配清楚地表明我需要覆盖equals(Object o)
对象类中的方法,该方法将比较 2d 形状。我通过比较形状区域和周长不尊重二维平面中的位置进行了比较。但这里的问题是,我不能使用抽象类Shape2d的抽象方法。因为我需要覆盖的方法equals(Objcet o)
,我不能转换成equals(Shape2d o)
。我能用它做什么?下面是我的代码。
/** This class is an abstract class and it is created for to be inherited specialized 2d shapes
* @version 02.26.2021
*/
public abstract class Shape2d
{
private int xLocation;
private int yLocation;
public Shape2d(int xLocation, int yLocation)
{
this.xLocation = xLocation;
this.yLocation = yLocation;
}
/** Getting the yLocation
* @version 02.26.2021
* @return
*/
public int getYLocation()
{
return yLocation;
}
/** Getting the xLocation
* @version 02.26.2021
* @return
*/
public int getXLocation()
{
return xLocation;
}
/** Abstact method which will be used for other 2d objects. Calculating the area of the 2d shape
* @version 02.26.2021
* @return
*/
public abstract double calculateArea();
/** Abstact method which will be used for other 2d objects. Calculating the perimeter of the 2d shape
* @version 02.26.2021
* @return
*/
public abstract double calculatePerimeter();
/** This method will calculate the distance of the two objects in absolute values.
* @param anyShape
* @return
*/
public double calculatingDistance(Shape2d anyShape)
{
if(anyShape instanceof Shape2d)
{
return Math.sqrt(Math.abs(Math.pow(yLocation - anyShape.yLocation,2) + Math.pow(xLocation - anyShape.xLocation, 2)));
}
return -1;
}
@Override
/** This method is Overrided. It will return the Cordinates of the center (x,y)
* @version 02.26.2021
*/
public String toString()
{
return "Center Cordinates of the Shape is: (" + xLocation +"," + yLocation + ")\n";
}
/** This method is overriding the equals method for finding out whether or not this shapes are the same
* disrespect to its position in the
* @version 02.26.2021
* @param anyShape
* @return
*/
public boolean equals(Shape2d anyShape)
{
return calculateArea() == anyShape.calculateArea() && calculatePerimeter() == anyShape.calculatePerimeter();
}
}
equals
接受一个Object
. 因此你必须使用public boolean equals(Object o)
. 参数类型是方法签名的一部分。如果您使用其他参数类型(Shape2d
而不是Object
),则它是方法重载而不是override。
但是,在方法的主体内,您可以将类型转换为Shape2d
. 当然,我们首先要检查是否o
实际上是 的实例Shape2d
,使用instanceof
.
if (o instanceof Shape2d) {
Shape2d s = (Shape2d) o;
// Do something with s
}
请注意,许多equals
实现使用this.getClass() == o.getClass()
.
正如评论中已经提到的,编译器只允许转换为与受转换的类型兼容的类。
Object o = (Object) someStringInstance
。String s = (String) someStringInstance
。LocalTime time = (LocalTime) someStringInstance
将发出编译错误。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句