面向对象(四)定义构造方法 构造方法的重载

定义构造方法

构造方法是一个特殊的成员方法,在定义时,有以下几点需要注意:

(1)构造方法的名称必须与类名一致。

(2)构造方法名称前不能有任何返回值类型的声明。

(3)不能在构造方法中使用return返回一个值,但是可以单独写return语句作为方法的结束。

案例

演示无参构造方法的定义


public class Student {
    public Student() {
        System.out.println("调用了无参构造方法");
    }
}
public class Example05 {
    public static void main(String[] args) {
        System.out.println("声明对象");
        Student stu=null;
        System.out.println("实例化对象");
        stu=new Student();
    }
}

程序运行结果

演示有参构造方法的定义与调用。

构建有参构造方法(确定参数之后-鼠标右击空白处,generate-construction-ctrl选择所有参数-ok

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void read(){
        System.out.println("我是:"+name+"年龄"+age);
    }
}
public class Example06 {
    public static void main(String[] args) {
        Student stu =new Student("张三",18);//实例化Student对象
        stu.read();
    }
}

Student类增加了私有属性name和age,并且定义了有参的构造方法Student (String name, int a)。

由运行结果可以看出,stu对象在调用read()方法时, name属性已经被赋值为张三,age属性已经被赋值为20。

构造方法的重载

与普通方法一样,构造方法也可以重载,在一个类中可以定义多个构造方法,只要每个构造方法的参数或参数个数不同即可。在创建对象时,可以通过调用不同的构造方法为不同的属性赋值

案例



public class Student {
    private String name;
    private  int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String name) {
        this.name = name;
    }
public void read(){
    System.out.println("我是:"+name+"年龄"+age);
}
}
public class Example07 {
    public static void main(String[] args) {
        Student stu1=new Student("张三");
        Student stu2=new Student("张三",18);
        stu1.read();
        stu2.read();
    }
}

Student:两个重载的构造方法

在创建stu1对象和stu2对象时,根据传入参数个数不同,stu1调用了只有一个参数的构造方法;stu2调用的是有两个参数的构造方法。