如何在不重命名的情况下两次使用实例变量?

Eur*_*uru 3 java

帮助,我刚刚开始学习Java,我正在做的这个在线教程要求我创建一个属于类的实例.该实例应该首先创建为"Rectangle"对象,然后创建为"Circle"对象.但Eclipse要求我重命名第二个"drawObject".

public class TestPolymorph {

    public static void main(String[] args) {

        Shape drawObject = new Rectangle(40,60);
        drawObject.draw();

        Shape drawObject = new Circle(40);
        drawObject.draw();

    }
}
Run Code Online (Sandbox Code Playgroud)

Ran*_*ndy 12

您将两次声明变量.相反,通过在第二个实例化中删除类型声明来覆盖它:

public class TestPolymorph {

    public static void main(String[] args) {

        Shape drawObject = new Rectangle(40,60);
        drawObject.draw();

        drawObject = new Circle(40);
        drawObject.draw();

    }
}
Run Code Online (Sandbox Code Playgroud)

我鼓励您将名称更改为更有意义的值:

public class TestPolymorph {

    public static void main(String[] args) {

        Shape rectangleShape = new Rectangle(40,60);
        rectangleShape.draw();

        Shape circleShape = new Circle(40);
        circleShape.draw();

    }
}
Run Code Online (Sandbox Code Playgroud)