面向对象编程(基础)——4.构造方法

构造方法

public class Employee {
    private String name;
    private double salary;
    private LocalDate hireDay;
    public Employee(String n, double s, int year,int month,int day) {
        name = n;
        salary = s;
        hireDay = LocalDate.of(year,month,day);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public LocalDate getHireDay() {
        return hireDay;
    }
    public void raiseSalary(double byPercent){
        double raise = salary*byPercent/100;
        salary += raise;
    }
}
 public Employee(String n, double s, int year,int month,int day) {
        name = n;
        salary = s;
        hireDay = LocalDate.of(year,month,day);
    }

构造器与类同名,在构造Employee类的对象时,构造器会运行,从而将实例字段初始化为所希望的初始状态。、
例如,使用下面这条代码创建Employee类的实例时:

new Employee("Vicky",100000,1997,4,24)

会将实例字段设置为:

name = "Vicky";
salary = 100000
hireDay = LocalData.of(1997,4,24)

构造器的一些内容:

  1. 构造器与类同名
  2. 每个类可以有一个以上的构造器
  3. 构造器可以有0个,1个或多个参数
  4. 构造器没有返回值
  5. 构造器总是伴随着new操作符一起调用

构造方法的重载

public class User {
    int id; // id
    String name; // 账户名
    String pwd; // 密码
    public User() {
 
    }
    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
    public static void main(String[] args) {
        User u1 = new User();
        User u2 = new User(1, "vicky");
        User u3 = new User(2, "Lili", "123456");     
    }
}

如果方法构造中形参名与属性名相同时,需要使用this关键字区分属性与形参。
this.id 表示属性id;id表示形参id

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值