Menu
CoddyTech

使用构造函数

Coddy Java 类和对象基础 课程的第 11 课,共 12 课。

使用 new 关键字创建对象时,我们总会执行一个构造方法(我们在类这一章中学过)。默认情况下,Java 中的每个类都有一个空构造方法,如下所示:

class MyClass {
	public MyClass() {
	
	}
}

使用下面的语句时:

MyClass myObj = new MyClass();

实际上,我们执行了这个不可见的构造方法!

如前所学,假设有一个类:

class Point {
	int x;
	int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

现在,我们可以使用这个构造方法创建多个对象,如下所示:

Point p1 = new Point(5, 3);
Point p2 = new Point(1, 2);
Point p3 = new Point(0, 0);
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

challenge icon

挑战

简单

给定的代码中有一个名为 Animal 的类,在 main 方法中:

  • 创建一个名为 cow、类型为 Animal 的对象,其 type 为 "cow",voice 为 “Moo”
  • 创建一个名为 dog、类型为 Animal 的对象,其 type 为 "dog",voice 为 “Woof”

亲手试试

class Animal {
    String type;
    String voice;
    
    public Animal(String type, String voice) {
        this.type = type;
        this.voice = voice;
    }
}

class Main {
    public static void main(String[] args) {
        // 在这里编写代码
        
        // 不要修改这行以下的代码
        System.out.println(cow.type + " is making " + cow.voice);
        System.out.println(dog.type + " is making " + dog.voice);
    }
}

Java 类和对象基础中的所有课

自己练习: Java 在线编译器