一、先看一下C++的构造函数
二、新建Dog.java文件和DogTest.java文件

三、将第一步中的C++代码稍微改动,变成Java代码
Dog.java代码
class Dog{
private String name;
public void setName(String Name) {
this.name = Name;
}
public String getName() {
return this.name;
}
// 不带参数的构造方法
public Dog() {
System.out.println("Dog's constructor method is invoked!");
}
// 带参数的构造方法
public Dog(String Name) {
this.name = Name;
System.out.println("Dog's constructor method with name is invoked!");
}
public void run() {
System.out.println(this.name + " is running");
}
}
DogTest.java代码
class DogTest {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.setName("Wang Cai");
dog1.run();
Dog dog2 = new Dog("Xiao Bai");
dog2.run();
}
}
四、打开命令行窗口,编译、运行


加入少儿信息学奥赛学习QQ群请扫左侧二维码,关注微信公众号请扫右侧二维码
QQ群和公众号.png
网友评论