展开全部
JAVA中new关键词的用法,就是创建一个对象,当创建对象时会调用对应的构造函数,如下例子:package com.test;
public class Employee {
/**
* 员工62616964757a686964616fe78988e69d8331333363376533编号
*/
private String number;
/**
* 员工姓名
*/
private String name;
/**
* 员工薪水
*/
private double salary;
/**
* 无参数构造函数
*/
public Employee() {
System.out.println("调用了构造函数方法一");
}
/**
* 给属性赋值构造函数
* @param number
* @param name
* @param salary
*/
public Employee(String number, String name, double salary) {
super();
this.number = number;
this.name = name;
this.salary = salary;
System.out.println("调用构造函数方法二");
}
public static void main(String[] args) {
//员工一,并且构造函数里设置值
Employee e1 = new Employee("e0001", "xiaoming", 5000.0);
System.out.println("员工一:" + e1);
//员工二,用set设置值,get的话可以获取到员工某个属性
Employee e2 = new Employee();
e2.setName("小二");
e2.setNumber("e0002");
e2.setSalary(5500.1);
System.out.println("员工二:" + e2);
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
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;
}
@Override
public String toString() {
return "Employee [number=" + number + ", name=" + name + ", salary=" +
salary + "]";
}
}
运行结果:
调用构造函数方法二
员工一:Employee [number=e0001, name=xiaoming, salary=5000.0]
调用了构造函数方法一
员工二:Employee [number=e0002, name=小二, salary=5500.1]