用Java创建对象

时间:2015-09-10 04:02:59

标签: java

这是代码

public class CreateObjectDemo {
    public static void main(String[] args){
        Point    originOne     = new Point(23,94);
        Rectangle rectOne = new Rectangle(originOne, 100,200);
        Rectangle rectTwo = new Rectangle(50,100);

        System.out.println("Width of rectOne : " + rectOne.width);
        System.out.println("Height of rectOne : "  + rectOne.height);
        System.out.println("Area of rectOne:" + rectOne.getArea());

        rectTwo.origin = originOne;

        System.out.println("X postion of rectTwo: " + rectTwo.origin.x);
        System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);

        rectTwo.move(40, 72);
        System.out.println("X position of rectTwo : " + rectTwo.origin.x);
        System.out.println("Y position of rectTwo : " + rectTwo.origin.y);
    }
}`

我有来自Java教程的代码,但是我在运行它时遇到了麻烦,它显示了" Point"和"矩形" ,错误说"点" &安培; "矩形"不能解析成一个类型。我在这里错过了什么? 我是Java的初学者,所以我很傻。

2 个答案:

答案 0 :(得分:1)

添加导入语句

import java.awt.Point;
import java.awt.Rectangle;

答案 1 :(得分:1)

看起来您正在使用的教程来自以下链接:

http://www.java2s.com/Code/Java/Class/CreateObjectDemo.htm

教程中的代码有效。您似乎没有将“Point”和“Rectangle”类复制到您的文件中。这是你需要做的:

  1. 将整个教程代码复制到名为“CreateObjectDemo.java”
  2. 的文件中
  3. 在命令行上运行“javac CreateObjectDemo.java”
  4. 在命令行上运行“java CreateObjectDemo”
  5. Width of rect_one: 100
    Height of rect_one: 200
    Area of rect_one: 20000
    X Position of rect_two: 23
    Y Position of rect_two: 94
    X Position of rect_two: 40
    Y Position of rect_two: 72