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

定义构造方法

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

(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调用的是有两个参数的构造方法。 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩气长存在心中

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值