构造方法的介绍(猫咪项目2)

本文介绍了构造方法的关键特点,包括与类同名、无返回值,并详细解析了构造方法的调用时机和规则,特别是在对象实例化时的使用。还讨论了在构造方法中如何避免值传递错误,提出了解决方案,如修改参数名和利用`this`关键字来正确赋值。同时提到了`this`在调用其他构造方法和方法中的作用。
摘要由CSDN通过智能技术生成

学习总结:
1、构造方法的特点
(1)构造方法与类同名且没有返回值
(2)语句格式
public 构造方法名(){
//初始化代码
}

(3)只能在对象实例化的时候调用。不能在方法中调用构造方法,同一个类的构造方法的调用只能在构造方法之间进行。【通过this();】

(4)当没有指定构造方法时,系统会自动添加无参的构造方法,当有,系统就不在添加。
出现问题:值未被正确传入
在这里插入图片描述
在这里插入图片描述
原因:就近原则
更正方案:
First:对name进行重命名(修改输入参数的参数名)
在这里插入图片描述
Second:使用this关键字,将值赋给当前对象,避免赋值不对称。
在这里插入图片描述
扩展:
this还可以用来调用方法。
在这里插入图片描述
在这里插入图片描述

package com.animals;

public class Cat {
	//成员属性:昵称、年龄、体重、品种
	String name;
	int month;
	double weight;
	String species;
public Cat(){
	System.out.println("我是无参构造方法");
}
public Cat(String name,int month,double weight,String species){
	this();
	this.name=name;
	this.month=month;
	this.weight=weight;
	this.species=species;
}
	//方法:跑到、吃东西
public void run(){
	this.eat();
	System.out.println("小猫快跑");
	}
public void run(String name){
	this.eat();
	System.out.println(name+"快跑");
}
public void eat(){
	System.out.println("小猫吃鱼");
}
}

package com.animals;

public class CatTest {
      public static void main(String[] args){
          Cat one=new Cat("花花",2,1000,"英国短毛猫"); 
         // one.run();
          System.out.println("昵称:"+one.name);
          System.out.println("年龄:"+one.month);
          System.out.println("体重:"+one.weight);
          System.out.println("品种:"+one.species);
          one.run(   );
      }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值