构造方法




1. 构造方法是一个特殊的方法,构造方法名字必须与类名一致,构造方法必须没有返回类型,也就是不编写返回类型
  1. 分类

    • 隐式

      当在一个类中,没有手动编写构造方法,则系统会提供一个默认的无参的构造方法

    • 显示


  2. 构造方法的执行

    当创建对象时自动执行相匹配的构造方法

    	Dog d = new Dog();//括号装参数列表
    
  3. 语法格式:

    public 方法名称([参数列表]){

     ...
    

    }

class Dog{
	//无参构造方法
	public Dog(){
		//完成对品种、颜色、名字、年龄、性别
		strain = "土狗";
		color = "黑色";
		name = "旺财";
		age = 5;
		sex = '公';
	}
	//编写带参构造方法,完成对属性品种、颜色、名字
	public Dog(String strain,String color,String name){
		//完成局部变量的值,赋给成员变量
		this.strain = strain;
		this.color = color;
		this.name = name;
	}
	//编写对所有属性赋值的构造方法
	public Dog(String strain,String color,String name,int age,char sex){
		this.strain = strain;
		this.color = color;
		this.name = name;
		this.age = age;
		this.sex = sex;
	}



原文地址:https://www.cnblogs.com/huochemeiyouhuo/p/12157751.html