【发布时间】:2021-04-14 11:23:20
【问题描述】:
我是 Java 的初学者,正在尝试学习 Java 中的多态性。我试着做一个简单的例子,但我的代码表现得很奇怪。所以这就是问题所在。我正在我的主要功能中创建一个圆圈,它来自 Shape。我的意思是;
Shape sc = new Circle();
当我尝试访问 Circle 类函数之一时,在该行之后,我无法在我的自动代码完成中看到该函数。我的意思是;
sc.getArea() //is not working
如果有人可以帮助我,我将不胜感激......
这是我的 Circle 类:
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方法,而sc是Shape,那么为什么您的IDE 会建议一个不属于该类的方法呢?
标签: java class oop polymorphism