Java创建对象数组然后构造方法实例化,如下:
package com.test;
import java.util.Arrays;
public class Employee {
/**
* 员工编号
*/
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对象数组为2长度
Employee[] emp=new Employee[2];
//员工一(实例化),并且构造函数里设置值
Employee e1 = new Employee("e0001", "xiaoming", 5000.0);
//员工二(实例化),用set设置值,get的话可以获取到员工某个属性
Employee e2 = new Employee();
e2.setName("小二");
e2.setNumber("e0002");
e2.setSalary(5500.1);
//将实例化的对象存进数组中
emp[0]=e1;
emp[1]=e2;
System.out.println("实例化的数组对象为:"+Arrays.toString(emp));
}
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]]
对象数组,创建数组后,数组的各元素,还有初始化的——创建对象实例的
public class Demo{
private Integer[] array;
Demo(Integer[] array){
this.array = array;
}
}
这个是你自己想着写的还是看视频写的??