创建一个Student类,其成员变量name(姓名),age(年龄),sex(性别)为私有变量,成员方法:say()、无参和带1个参、2个参和3个参的构造方法Student()
在主方法中使用new 创建四个Student对象stu1、stu2、stu3和 stu4;
通过调用无参构造方法实现对stu1三个属性赋值;
通过调用1个参的构造方法实现对stu2三个属性赋值;
通过调用2个参的构造方法实现对stu3三个属性赋值;
通过调用3个参的构造方法实现对stu4三个属性赋值;
调用stu1、stu2、stu3和 stu4的say()方法.
public class Student {
private String name;
private int age;
private String sex;
public Student() {}
public Student(String name) {
this.name = name;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void say(){
System.out.println("学生会说话");
}
public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student("张三");
Student stu3 = new Student("李四",20);
Student stu4 = new Student("王五",20,"男");
stu1.say();
stu2.say();
stu3.say();
stu4.say();
}
}
运行结果:
public class Student {
private String name;
private int age;
private String sex;
public Student() {
}
public Student(String name) {
this.name = name;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void say(){
System.out.println(this);
}
public static void main(String[] args) {
Student stu1 = new Student();
Student stu2 = new Student("张三");
Student stu3 = new Student("李四",18);
Student stu4 = new Student("王五",20,"男");
stu1.say();
stu2.say();
stu3.say();
stu4.say();
}
}
这代码不是可以自动生成吗
最多写个say方法