构造方法可以被重载 ,来表达对象的多种初始化行为。
构造方法有什么具体意义:
当一个类需要实例化多个对象时,重载构造方法能够使程序变简洁,减少代码量,提高效率。
for example:
public class Human {
public String name;
public String sex;
public int age;
public void eat(){
System.out.println(name+sex+"吃饭");
}
public void run(){}
}
public class Test {
public static void main(String[] args){
Human h1 = new Human();
h1.name = "jack";
h1.sex = "男";
h1.age = 15;
Human h2 = new Human();
h2.name = "zhangsan";
h2.sex = "女";
h2.age = 18; //没有构造方法时,每重新实例化一个对象,都要重复对变量进行赋值的操作,使程序繁琐,工程量大。
h1.eat();
h2.eat();
}
}
——————————————————————
public class Human {
public String name;
public String sex;
public int age;
public Human(){
}
public Human(String name){
this.name = name;
}
public Human(String name,String sex)
this.name = name;
this.sex = sex;
}
public Human(String name,String sex,int age){
this.name = name;
this.sex = sex;
this.age = age;
}
public void eat(){
System.out.println(name+sex+"吃饭");
}
}
public class Test {
public static void main(String[] args){
Human h1 = new Human("jack","男",15);
Human h2 = new Human("zhangsan","男",22);
Human h3 = new Human("lisi","男",33);//重载构造方法后,可以直接通过传参的方式,
直接对各个对象的变量进行赋值,减少代码量。
h1.eat();
h2.eat();
h3.eat();
}
}