定义类Teacher有属性nameagecollegedepartment 构造方法有无参的无参的构造方法内给四个属性赋值为老师0大学系部有两个参数的构造方法给name和age赋值有四个参数的构造方法给四个属性赋值在四个参数的构造方法内通过this调用两个参数的构造方法。有方法printInfo 用于输出四个属性的值。测试类TeacherTest定义一个Teacher对象t1t2t3用无参的构造方
public class Teacher {
private String name;
private int age;
private String college;
private String department;
public Teacher() {
this.name = "老师";
this.age = 0;
this.college = "大学";
this.department = "系部";
}
public Teacher(String name, int age) {
this();
this.name = name;
this.age = age;
}
public Teacher(String name, int age, String college, String department) {
this(name, age);
this.college = college;
this.department = department;
}
public void printInfo() {
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.println("学校:" + college);
System.out.println("系别:" + department);
}
}
public class TeacherTest {
public static void main(String[] args) {
Teacher t1 = new Teacher();
Teacher t2 = new Teacher("张三", 30);
Teacher t3 = new Teacher("李四", 35, "中山大学", "计算机科学系");
t1.printInfo();
System.out.println("--------------");
t2.printInfo();
System.out.println("--------------");
t3.printInfo();
}
}
原文地址: http://www.cveoy.top/t/topic/bix0 著作权归作者所有。请勿转载和采集!