Java面向对象之构造方法、构造方法重载

一、构造方法

1、简单说明
在创建对象时,自动调用的方法为构造方法,它没有返回值,最大的作用就是用来存放类的属性信息(存放、转换)。同时,在定义类的时候,java会给每一个类都提供一个默认无参构造函数,即:

public 类名(){
	//无方法体
}

因此我们在新建对象时,都需要new 类名();也就是类名后面加个括号来调用默认无参构造函数。

2、不使用构造方法

public class Test01_Chair{
    
    
	String color;
	String position;
	int size = 10;
	
	//定义描述椅子状态的方法(使用this指针来引用类的属性)
	public void state(){
    
    
		System.out.println("一张" + color + "色的椅子在" + position);
	}
	
	//定义主函数
	public static void main(String[] args){
    
    
		Test01_Chair c1 = new Test01_Chair();  //通过椅子类实例化对象c1
		c1.color = "红";  //修改对象的参数
		c1.position = "客厅";
		
		Test01_Chair c2 = new Test01_Chair();  //通过椅子类实例化对象c1
		c2.color = "棕";  //修改对象的参数
		c2.position = "卧室";
		
		c1.state();  //调用对象的方法,输出状态
		c2.state();
	}
}

可以看到,在每次创建对象时都需要单独给对象的属性赋值,显得很麻烦。

1.2.1

3、使用构造方法

public class Test01_Chair{
    
    
	String color;
	String position;
	int size = 10;
	
	//定义椅子的构造方法
	public Test01_Chair(String color, String position){
    
    
		//属性值等于传进构造方法的参数值
		this.color = color;  
		this.position = position;
	}
	
	//定义描述椅子状态的方法(使用this指针来引用类的属性)
	public void state(){
    
    
		System.out.println("一张" + color + "色的椅子在" + position);
	}
	
	//定义主函数
	public static void main(String[] args){
    
    
		//定义了构造方法后:在创建对象时就需要传入参数了
		Test01_Chair c1 = new Test01_Chair("红色","客厅");  //通过椅子类实例化对象c1
		Test01_Chair c2 = new Test01_Chair("棕色","卧室");  //通过椅子类实例化对象c1
		
		c1.state();  //调用对象的方法,输出状态
		c2.state();
	}
}

使用了构造方法,在每次创建对象时,传入参数,就会将参数赋值为对象的属性,在调用和其他操作时就显得很方便了。

二、构造方法重载

1、简单说明
构造方法的名字相同,但是参数的个数或类型不同,这个时候就需要用到构造方法重载。也就是创建类时使用同一个类名,但是调用的是不同的构造函数。这样可以让我们有更多的方式、更自由地去创建对象。

2、重载构造练习

public class Test01_Chair{
    
    
	String color;  //椅子颜色
	String position;  //椅子所处位置
	int size;  //椅子的大小
	
	//定义椅子的构造方法
	public Test01_Chair(String color, String position){
    
    
		//属性值等于传进构造方法的参数值
		this.color = color;  
		this.position = position;
	}
	//定义椅子的重载构造方法(同名不同参构造方法)
	public Test01_Chair(String color, String position, int size){
    
    
		//技巧:在构造方法中可以使用this()调用构造方法,
		//因此在此处可以直接利用上一个构造方法的属性赋值
		this(color, position);
		//同时,在添加一个属性赋值
		this.size = size;
	}
	
	//定义描述椅子状态的方法(使用this指针来引用类的属性)
	public void state(){
    
    
		System.out.println("一张" + color + size + "寸大的的椅子在" + position);
	}
	
	//定义主函数
	public static void main(String[] args){
    
    
		//定义了构造方法后:在创建对象时就需要传入参数了
		Test01_Chair c1 = new Test01_Chair("红色","客厅");  //通过椅子类实例化对象c1
		Test01_Chair c2 = new Test01_Chair("棕色","卧室");  //通过椅子类实例化对象c2
		//调用重载构造方法
		Test01_Chair c3 = new Test01_Chair("灰色","厨房",12);  //通过椅子类实例化对象c3
		
		//调用对象的方法,输出状态
		c1.state();  
		c2.state();
		c3.state();
	}
}

2.2.1

猜你喜欢

转载自blog.csdn.net/Viewinfinitely/article/details/119952798