多态性在我的Java代码中不起作用



我是Java的初学者,正在尝试学习Java中的多态性。我试着做一个简单的例子,但我的代码表现得很奇怪。所以这就是问题所在。我正在我的主函数中创建一个圆,它来自于Shape。我的意思是;

Shape sc = new Circle();

在那一行之后,当我试图访问Circle类函数之一时,我在自动代码完成中看不到该函数。我的意思是;

sc.getArea() //is not working

如果有人能帮助我,我将不胜感激。。。

这是我的Circle Class:

public class Circle extends Shape {
public double radius;
public Circle() {
this.radius = 1.0;
}
public Circle(double radius) {
this.radius = radius;
}
public Circle(String color, boolean filled, double radius) {
super(color, filled);
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
double area;
area = PI * radius * radius;
return area;
}
public double getPerimeter() {
double perimeter;
perimeter = (2*radius)*PI;
return perimeter;
}
@Override
public String toString() {
return "A Circle with radius "+this.radius+", which is a subclass of Shape";
}
}

这是我的形状类:

public class Shape {
public String color;
public boolean filled;
public static final double PI = 3.14;
public Shape(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public Shape(){
this.color = "Green";
this.filled = true;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
@Override
public String toString() {
if(this.filled){
return "A Shape with color of " + this.color +" and filled";
}
else
return "A Shape with color of " + this.color +" and not filled";
}
}

这是我的主要功能:

public class ShapeMain {
public static void main(String[] args) {
Circle circle = new Circle(2.0);
Square square = new Square(2.0);
Rectangle rectangle = new Rectangle(2.0,3.0);
Shape sc = new Circle(2.0);
Shape ss = new Square(2.0);
Shape sr = new Rectangle(2.0,3.0);
// sc.getArea() ... is not working
//Polymorphisim is not working
}
}

Shape没有名为getArea()的方法,因此编译器不允许您调用该方法。

要查看多态性的作用,一个简单的方法是定义Shapeabstract,并添加一个abstract getArea()方法:

public abstract class Shape {
// ... all the stuff you already have
public abstract double getArea();
}

您可以简单地保持代码的其余部分不变,现在可以对任何类型为Shape的变量调用getArea()

当然,每个扩展Shape的非abstract类现在都必须为getArea()方法提供一个实际的实现(即代码(。

您必须强制转换sc对象才能访问Circle类的函数:

Shape sc = new Circle();
Circle circle = (Circle) sc;
circle.getArea();

因此,您使用的是同一个对象(不是实例化新对象(,但以不同的方式表示:首先是形状,然后是圆。

强制转换不会丢失任何属性值。

你非常接近。以下是您在示例中需要做的操作:由于变量是"形状",因此只能要求它执行"形状"所能执行的操作。所以,如果你想让它获取面积,Shape必须有一个方法getArea。如果将Shape的getArea方法抽象化,Java将把调用重定向到Circle的getArea。

相关内容

最新更新