• java对象构造


    重载

    构造方法与方法都可以重载,多个方法有相同名字不同参数即可产生重载
    用方法名和参数名来描述一个方法叫做方法签名,返回类型不属于方法签名

    默认初始化

    趋于“0”(0,false,null)

    无参构造器

    显示域初始化

    程序清单21行

    参数名

    技巧:每个参数前加个a或其他字母,这样参数含义清晰易懂
    程序清单第37行

    调用另一个构造器

    构造器第一个语句形式为this(…),则该构造器会调用同一个类另一个构造器

    程序清单

    import java.util.Random;
    
    public class ConstructorTest {
        public static void main(String[] args) {
            Employee[] staff = new Employee[3];//创建一个引用类型的数组长度为3
    
            staff[0] = new Employee("Harry",4000);
            staff[1] =  new Employee(6000);
            staff[2] = new Employee();
    
            //打印输出Employee对象
            for (Employee aEmpoyee : staff)
                System.out.println("name="+aEmpoyee.getName()+",id="+aEmpoyee.getId()+",salary="+ aEmpoyee.getSalary());
        }
    }
    
    class Employee{
        private static int nextId;
    
        private int id;
        private String name = "";//实例域初始化
        private double salary;
    
        static //静态初始化块
        {
            Random generator = new Random();
            //将nextId设置为0~9999之间的随机数
            nextId = generator.nextInt(10000);
            System.out.println(nextId);
        }
        //对象初始化块
        {
            id = nextId;
            nextId++;
        }
        //三个重载构造方法
        public Employee(String aName,double aSalary){
            name = aName;
            salary = aSalary;
        }
    
        public Employee(double aSalary)
        {
            this("Employee #" + nextId,aSalary);
        }
    
        public Employee(){
    
        }
    
        public String getName(){
            return name;
        }
    
        public double getSalary(){
            return salary;
        }
    
        public int getId(){
            return id;
        }
    
    }
    
    
  • 相关阅读:
    记录s标签范例
    链表问题总结
    Hibernate学习总结
    HDU2460-Network
    CF464C-Substitutes in Number
    CF666E-Forensic Examination
    CF373C-Counting Kangaroos is Fun
    CF558E-A Simple Task
    HDU5669-Road
    CF341D-Iahub and Xors
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860169.html
Copyright © 2020-2023  润新知