带参构造方法

package cn.hpu.animal;

public class CatTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//对象实例化
		Cat one=new Cat("花花",3,"中华田园猫");
		Cat two=new Cat();
		
		//测试
//		one.eat();
//		one.run();
//		one.name="花花";
//		one.month=2;
//		one.weight=2.5;
//		two.name="帆帆";
//		two.month=5;
//		two.weight=3;
		System.out.println("昵称"+one.name);
		System.out.println("年龄"+one.month);
		System.out.println("体重"+one.weight);
//		System.out.println("昵称"+two.name);
//		System.out.println("年龄"+two.month);
//		System.out.println("体重"+two.weight);
//		


	}

}
package cn.hpu.animal;
/**
 * 宠物猫类
 * @author Hongliang Wang
 *
 */
public class Cat {

	//成员属性:年龄,昵称,体重,品种
	//注意成员变量的位置:在cat类内,在方法以外。
	String name;//String 默认值为null
	int month;  //int默认值为0
	double weight;//double默认值为0.0,这些是系统给成员属性赋的初值
	String species;
	
	public Cat() {
		System.out.println("无参构造方法被调用");
	}
	public Cat(String name) {
		System.out.println("有参数被调用");
	}
	public Cat(String name,int month,String species) {
		name=name;
		month=month;
		species=species;
		System.out.println("");
	}
	//成员方法:跑动,吃东西
	//跑动的方法
	public void run(){
		System.out.println("小猫会跑");
		
	}
	public void run(String name) {
		System.out.println(name+"快跑");
		
	}
	//吃东西的方法
	public void eat() {
		System.out.println("小猫吃鱼");
	}
	

}

运行结果:

问题描述:我在Cat类中定义了一个有参数的构造方法,但是在调用该构造方法的时候,向构造方法中传入了参数,参数的值并没有复制给成员属性。

调用构造方法的代码是:Cat one=new Cat("花花",3,"中华田园猫");

我找到这个构造方法之后发现我的参数列表中的参数和成员属性是一样的。

由于程序执行的“就近原则”,我传入的参数就会赋值给最近的同名的参数名进行赋值,也就是自己赋值给自己了。

解决方法1:我把构造方法中的形式参数的名字给改了,没有和成员属性的名字相同。

public Cat(String Newname,int Newmonth,String Newspecies) {
		name=Newname;
		month=Newmonth;
		species=Newspecies;
	}

方法一显然是有些繁琐的,因为它还要限制构造方法的参数名字,我还要费心起名字。那么有没有一种方法既简单又能让程序知道我是给属性赋值呢?答案是有。

方法二:使用this关键字。java中this关键字的作用一句话概括就是:“哪个对象调用this所在的函数,this就代表哪个对象”

解决代码如下:

public Cat(String name,int month,String species) {
		this.name=name;
		this.month=month;
		this.species=species;
	}


 

猜你喜欢

转载自blog.csdn.net/ll123c/article/details/86153236