关于方法重载

本文详细介绍了Java中构造器的概念及其重载的使用方法。通过具体的代码示例,展示了如何利用不同参数列表来实现多样化的对象初始化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法重载的出现:

当我们使用一个变量时,我们需要对其进行初始化。在java中,构造器就是完成对象的初始化。构造器的名字与类的名字相同,这样子做的好处:

1、可以避免构造器的名字与其他变量的名字相同

2、编译器能够更好的找到构造器。

而默认的构造器的方法单一,无法满足其他情况下的初始化需要,于是便产生了方法名字相同、参数列表不一样的方法重载。参数列表就涉及到参数的类型、参数的个数、参数的顺序。在一般情况,不赞成因参数顺序的不同而造成的方法重载,因为这样子做不利于日后的维护。而其中方法返回值也有不同,但单依靠返回值的不同而区分方法的不同,在调用方法的时候可能会造成困扰。

这样子的做法也可以推广到一般的方法中。

构造器中的方法重载的使用:

public class ConstrutorTest{
	String str;
	int n ;
	char ch;
	
	public ConstrutorTest() {
		this("I love you!",999,'b');//调用三个参数的构造器
		//this.("I love you!",999);不允许调用两个构造器
		System.out.println("I come from Construtor " +
		"which have the parameter of blank");
	
	}
	
	public ConstrutorTest(String str) {
		this.str = str;
		System.out.println("I come from Construtor " +
		"which has the parameter of String str");
	}
	
	public ConstrutorTest(int n) {
		this.n = n;
		System.out.println("I come from Construtor " +
		"which has the parameter of int n");
	}
	
	public ConstrutorTest(String str,int n) {
		this.str = str;
		this.n = n;
		System.out.println("I come from Construtor " +
		"which have the parameters of String str,int n");
	}
	
	public ConstrutorTest(String str,int n,char ch) {
		this(str,n);
		this.ch = ch;
		System.out.println("I come from Construtor " +
		"which have the parameters of String str,int n,char ch");
	}
	
	public static void main(String[] args) {
		ConstrutorTest ct = new ConstrutorTest();
		System.out.println(ct.str);
		System.out.println(ct.n);
		System.out.println(ct.ch);
	}
}

运行结果:

 I come from Construtor which have the parameters of String str,int n
I come from Construtor which have the parameters of String str,int n,char ch
I come from Construtor which have the parameter of blank
I love you!
999
b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值