Java 构造方法

构造方法

1.使用 new + 构造方法创建一个新对象

2.构造方法是定义在Java类中的一个用来初始化对象的方法

3.构造方法没有返回值类型,与类同名

4.构造方法虽然没有返回值类型,但是可以写return,用于去规避一些不合常理的数据。

构造方法的语句格式

 无参构造方法的使用

public class test6 {
    public static void main(String[] args) {
        
        Car c1 = new Car();
    }
}

class Car{
    
    public Car() {
        // TODO Auto-generated constructor stub
        System.out.println("无参数的构造方法~~~");
    }
}

运行结果:

无参数的构造方法~~~

运行结果说明,在实例化一个对象时,其实是调用了构造方法。

有参的构造方法

为什么会有有参的构造方法呢?

其实目的只有一个,就是为了初始化成员变量的值。

class Car{
    int tread;
    int seat;
    
    public Car() {
        System.out.println("无参数的构造方法~~~");
    }
    
    public Car(int newTread, int newSeat){
        tread = newTread;
        seat = newSeat;
        System.out.println("轮胎:"+tread+"  座椅:"+seat+"   有参数的构造方法~~~");
    }
}

public class test6 {
    public static void main(String[] args) {
        Car c1 = new Car(4, 7); // 调用有参构造函数
        Car c2 = new Car();     // 调用无参构造函数
    }
}

运行结果:

轮胎:4  座椅:7   有参数的构造方法~~~
无参数的构造方法~~~

构造方法的重载

方法名相同,但参数不同的多个方法,调用时会自动根据不同的参数选择相应的方法。

class Car{
    int tread;
    int seat;
    
    public Car(int newTread) {
        tread = newTread;
        System.out.println("轮胎:"+tread+"无参数的构造方法~~~");
    }
    
    public Car(int newTread, int newSeat){
        tread = newTread;
        seat = newSeat;
        System.out.println("轮胎:"+tread+"  座椅:"+seat+"   有参数的构造方法~~~");
    }
}

public class test6 {
    public static void main(String[] args) {
        Car c1 = new Car(4, 7); // 调用第二参构造函数
    }
}

运行结果:

轮胎:4  座椅:7   有参数的构造方法~~~

运行结果表明,程序会跟根据实例化对象时传入的参数的个数选择调用哪个构造方法。

构造方法给对象赋值

构造方法不但可以给对象的属性赋值,还可以保证给对象赋一个合理的值

class Car{
    int tread;
    int seat;
    
    public Car(int newTread, int newSeat){
        if(tread<4)    {    // 汽车都有4个轮子,如果传入3个轮子就会自动改成4个轮子
            tread = 4;
            System.out.println("输入有误!自动更正为4");
        }
        else
            tread = newTread;
        seat = newSeat;
        System.out.println("轮胎:"+tread+"  座椅:"+seat+"   有参数的构造方法~~~");
    }
}

public class test6 {
    public static void main(String[] args) {
        Car c1 = new Car(3, 7); // 调用第二参构造函数
    }
}

运行结果:

输入有误!自动更正为4
轮胎:4  座椅:7   有参数的构造方法~~~

构造方法中return的使用

return存在的意义就是判断构造方法传入的参数是否合理。

public class ClassTest01{
    public static void main(String[] args) {
        Car c1 = new Car(3, 6);
    }
}

class Car{
    int tread;
    int seat;
    
    public Car(int newTread, int newSeat){

        tread = newTread;
        if(tread<4)        // 汽车都有4个轮子,如果传入3个轮子就会自动改成4个轮子
            return ;    // 传入的值不合理,所以没有结果输出
        seat = newSeat;
        System.out.println("轮胎:"+tread+"  座椅:"+seat+"   有参数的构造方法~~~");
    }
}

注意:

1.有参构造函数和无参构造函数是可以共存的。

2.调用有参构造函数还是无参构造函数是看实例化对象时有没有传入参数,传入多少个参数,系统自动选择。

3.有构造函数时调用构造函数,没有时调用系统给的默认构造函数。

4.当没有指定构造方法时,系统会自动添加无参构造方法。

5.当有指定构造方法,无论是有参、无参的构造方法,都不会自动添加无参的构造方法。

原文地址:https://www.cnblogs.com/chuijingjing/p/9451292.html