Java学习(42)实例化对象

实例化对象

  1. 案例:宠物猫类
package com.study.animal;

public class CatTest {
	public static void main(String[] args) {
		// 对象实例化
		Cat one = new Cat();
	    // 测试
		System.out.println("昵称" + one.name);
		System.out.println("年龄" + one.month);
		System.out.println("体重" + one.weight);
		System.out.println("品种" + one.species);
		one.run();
//		one.Cat();

	}
}

运行结果:

昵称null
年龄0
体重0.0
品种null
小猫吃鱼
小猫快跑

注:
类中成员属性定义后系统会自动赋初始值的,而类的方法中定义的局部变量是没有默认初始值的。
2. 方法重载
对run方法进行重载:

public void run(String name){
		System.out.println(name+"快跑");
	}

在主方法内进行测试:

package com.study.animal;

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

	}
}

运行结果:

小猫吃鱼
小猫快跑
昵称:喵喵
年龄:2
体重:1000.0
品种:英国短毛猫
喵喵快跑
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值