【发布时间】:2016-04-17 05:11:10
【问题描述】:
我目前正在学习 Java,所以请原谅我的无知。这是我当前的代码
Shape.java
public interface Shape {
public abstract void draw();
}
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");
}
}
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
}
}
我当前的代码有什么问题吗,因为它不起作用。我的问题是如何创建一个属于Shape 类的drawObject 实例,并且在运行时drawObject 将使用两个参数创建,长度和宽度(例如给出40 和60),Rectangle 的绘制方法然后将被调用。
【问题讨论】:
-
你能详细说明“不工作”吗?给出例外还是不打印你所期望的?
标签: java inheritance polymorphism