Vui*_*inh 1 java polymorphism inheritance
我正在学习Java,所以请忍受我的无知.这是我目前的代码
Shape.java
public interface Shape {
public abstract void draw();
}
Run Code Online (Sandbox Code Playgroud)
Rectangle.java
public abstract class Rectangle implements Shape {
private final double width, length;
public Rectangle() {
this(1,1);
}
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
public void draw() {
System.out.println("A rectangle of sides " + length + " by " + width + " will be drawn");
}
}
Run Code Online (Sandbox Code Playgroud)
TestPolymorph.java
public class TestPolymorph implements Shape {
public static void main(String[] args) {
Shape[] drawObject = { new Rectangle(40, 60) };
drawObject[0].draw();
}
@Override
public void draw() {
// TODO Auto-generated method stub
}
}
Run Code Online (Sandbox Code Playgroud)
我当前的代码有什么问题,因为它不起作用.我的问题是如何创建drawObject属于Shape类的实例,并且在运行时drawObject将使用两个参数创建长度和宽度(例如给出40和60),Rectangle然后将调用draw方法.
小智 5
你很接近,确实没有必要让你的TestPolymorph实现Shape.这是你的驱动程序,而不是实现接口的模型,所以你可以把它关掉.
最后,从Rectangle类中删除摘要.这不是一个抽象类,因为您实际上需要该类型的实例.
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |