例如,我有这样的代码
Shape.java
x <- "Team-A - B"
teams <- strsplit(x, " - ", fixed=TRUE)[[1]]
teams
[1] "Team-A" "B"
Circle.java
public interface Shape{
double getArea();
}
Rectangle.java
public class Circle implements Shape {
private double radius;
public Circle(){
radius = 1.0;
}
public Circle(double radius){
this.radius = radius;
}
@Override
public String toString() {
return "Circle[radius=" + radius + "]";
}
@Override
public double getArea(){
return 3.14 * radius * radius;
}
}
还有TestShape.java文件
public class Rectangle implements Shape{
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public String toString() {
return "Rectangle[length=" + length + ",width=" + width + "]";
}
@Override
public double getArea() {
return length * width;
}
}
现在,我希望Circle类具有 getCircumference()方法,但是它正在运行找不到符号错误。不可能在实现接口的子类中添加额外的方法吗?如果有,该怎么做?
编辑:从Rectangle类中删除了getPerimeter()方法。尝试调用它时,还会导致相同的错误。
答案 0 :(得分:2)
您可以在已实现任何一个或多个接口但您正在使用接口引用访问该方法的类中添加任意数量的方法
Shape s = new Circle();
// So compiler see the reference of Shape interface and it did not have any `getCircumfrence() function
如果要访问类方法,则需要使用类引用
Circle s = new Circle()
答案 1 :(得分:0)
是的,有可能。只需将方法getCircumference()
添加到类Circle
,您将拥有它。
答案 2 :(得分:0)
在Rectangle.java
中已经有一个名为getPerimeter()
的方法,类似地,您可以在getCircumference()
中创建一个名为Circle.java
的方法