构造器详解

一、构造器规则

(1)构造器用于初始化
(2)构造器如何调用?必须用new来调用构造器,这样可以返回一个初始化完成的对象。
(3)如果不为一个类提供构造器,系统会自动为该类提供无参数的构造器。

二、构造器重载

一个类中可以定义多个构造器(构造器名相同),必须要求形参列表不同。

  • this引用:this紧跟一个.
  • this调用:this紧跟一个()

this调用代表调用同一个类中重载的构造器-----this调用只能出现在构造起的第一行。

public class Dog
{
	private String name;
	private String color;
	private int age;
	public Dog(String name,String color)
	{
		this.name = name;
		this.color = color;
	}
	public Dog(String name,String color,int age)
	{
		//this.name = name;
		//this.color = color;
		//调用重载构造器,具体调用哪个构造器由参数决定
		//this(name,color);
		this("aa","黄色");
		this.age = age;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public void setColor(String color)
	{
		this.color = color;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	public String getName()
	{
		return(this.name);
	}
	public String getColor()
	{
		return(this.color);
	}
	public int getAge()
	{
		return(this.age);
	}
}
public class DogTest
{
	public static void main(String[] args)
	{
		Dog d = new Dog("旺财","灰色",3);
		System.out.println(d.getName()); //aa
		System.out.println(d.getColor()); //黄色
		System.out.println(d.getAge()); //3
	}
}
posted @ 2020-02-05 16:23  又又又8  阅读(126)  评论(0)    收藏  举报