• 【java学习】构造方法重载(26)



    构造方法(构造器)的重载

    1. 构造器一般用来创建对象的同时初始化对象。如

        class Person{
            String name;
            int age;

            public Person(String n , int a){
            name=n; age=a;
            }

        }

    1. 构造器重载使得对象的创建更加灵活,方便创建各种不同的对象。
      构造器重载举例:

        public class Person{
            public Person(String name, int age, Date d) {this(name,age);...}
            public Person(String name, int age) {...}
            public Person(String name, Date d) {...}
            public Person(){...}
        }

    1. 构造器重载,参数列表必须不同

    举例1:

    package day06;
    
    public class Person6 {
    	/**
    	 * 构造器的重载,就是为了方便 调用方 可以灵活的创建出不同需要的对象
    	 * 重载的多个构造方法实际上就是相当于提供了多个初始化new对象的模版
    	 */
    	public Person6() {    //构造器的无参重载
    		
    	}
    	
    	public Person6(int a) {   //构造器的重载(有一个int参数)
    		
    	}
    	
    	public Person6(Sring n) {   //构造器的重载(有一个String参数)
    		
    	}
    	
    	public Person6(int a, String n) {    //构造器的重载(...)
    		age = a;
    		name = n;
    	}
    	
    	public int age;
    	public String name;
    	
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    举例2:

    public class Person {
    	private String name;
    	private int age;
    	private Date birthDate;
    	
    	public Person(String name, int age, Date d) {
    	this.name = name;
    	this.age = age;
    	this.birthDate = d;
    	}
    	
    	public Person(String name, int age) {
    	this(name, age, null);
    	//this.name=name; this.age=age; this.birthDate=null;
    	}
    	
    	public Person(String name, Date d) {
    	this(name, 30, d);
    	//this.name=name; this.age=30; this.birthDate=d;
    	}
    	
    	public Person(String name) {
    	this(name, 30); //this.name=name; this.age=30;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  • 相关阅读:
    【二叉树】——链式结构(快速掌握递归与刷题技巧)
    第十四届蓝桥杯省赛C++B组D题【飞机降落】题解(AC)
    (附源码)node.js自我展示博客网站 毕业设计 231547
    云原生Kubernetes:CRI 容器运行时接口
    vue;element-ui
    基于SSM的电影网站设计与实现
    IP-guard产品相关端口和服务名称
    Live555库结构及其核心概念
    【SpringBoot2】SSMP整合综合案例(上)
    [算法应用]关键路径算法的简单应用
  • 原文地址:https://blog.csdn.net/weixin_44883789/article/details/133798379