重載,this調用另一個構造器,無參數構造器,靜態初始化塊
package zzy;
import java.util.*;
import static java.lang.System.*;
public class zzy5 {
public static void main(String[] args){
Employee[] staff = new Employee[4];
staff[0] = new Employee("Harry",40000);
staff[1] = new Employee(60000.0);
staff[2] = new Employee(5);
staff[3] = new Employee();
for(Employee e : staff)
out.println("name=" + e.getName() + ",id="+e.getId()+",salary="+e.getSalary());
}
}
class Employee
{
private static int nextId;
private int id;
private String name = "";
private double salary;
static
{
Random generator = new Random();
nextId = generator.nextInt(10000);
}
{
id = nextId;
nextId++;
}
public Employee(String n,double s)
{
name = n;
salary = s;
}
public Employee(double s){
this("nizaina",s); //調用同一個類的public Employee(String n,double s)構造器
}
public Employee(int v ,double s)
{
name = "nihao";
salary = 150;
}
public Employee(int b)
{
this(2,5.2); //調用 public Employee(int v ,double s)構造器
}
public Employee()
{
//實例域name初始化爲“”,salary默認爲零;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
}
import java.util.*;
import static java.lang.System.*;
public class zzy5 {
public static void main(String[] args){
Employee[] staff = new Employee[4];
staff[0] = new Employee("Harry",40000);
staff[1] = new Employee(60000.0);
staff[2] = new Employee(5);
staff[3] = new Employee();
for(Employee e : staff)
out.println("name=" + e.getName() + ",id="+e.getId()+",salary="+e.getSalary());
}
}
class Employee
{
private static int nextId;
private int id;
private String name = "";
private double salary;
static
{
Random generator = new Random();
nextId = generator.nextInt(10000);
}
{
id = nextId;
nextId++;
}
public Employee(String n,double s)
{
name = n;
salary = s;
}
public Employee(double s){
this("nizaina",s); //調用同一個類的public Employee(String n,double s)構造器
}
public Employee(int v ,double s)
{
name = "nihao";
salary = 150;
}
public Employee(int b)
{
this(2,5.2); //調用 public Employee(int v ,double s)構造器
}
public Employee()
{
//實例域name初始化爲“”,salary默認爲零;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.