构造方法介绍

2-1 构造方法—无参构造方法

构造方法也称构造函数、构造器。

构造方法不能够被对象单独调用。

构造方法
1.当没有构造方法 系统会自动添加无参的构造方法
2.当有创建构造方法 无论有参无参 系统都不会再添加构造方法
3.一个类中可有多个构造方法
4.构造方法名与类名一定相同且没有返回值
5.构造方法使用 只能在对象实例化(new 了之后)时调用
6.与普通方法不同 只能通过new调用 不能通过对象调用

构造方法的语句格式

public 构造方法名(){

​ //初始化代码

}

2-2 构造方法—带参构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.imooc.animal;
/**

- 宠物猫类
- @author HeFeihong
*
*/

public class Cat {
//成员属性:昵称、年龄、体重、品种
String name;//昵称
int month;//年龄
double weight;//体重
String species;//品种

public Cat() {

}

public Cat(String name) {
System.out.println("我是带参构造方法");
}

public Cat(String newName,int newMonth,double newWeight,String newSpecies) {
name=newName;
month=newMonth;
weight=newWeight;
species=newSpecies;
}

//成员方法:跑动、吃东西
//跑动的方法
public void run() {
System.out.println("小猫快跑");
}

//吃东西的方法
public void eat() {
System.out.println("小猫吃鱼");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.imooc.animal;

public class CatTest {
public static void main(String[] args) {
//对象实例化
Cat one=new Cat("花花",2,1000,"英国短毛猫");
//测试
one.eat();
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);
}
}
1
2
3
4
5
6
7
就近:把传入的参数复制给了局部变量
全局变量没有改变
就近原则
赋值时,在你全局变量和局部变量名相同时,执行顺序会优先调用你局部变量。
结局方式
1. 修改输入参数的参数名
2. 使用this

this 关键字表示当前对象

上面的例子name=newName可改为this.name

编程练习:

编写自定义猴子类,按照效果图,在编辑器中对应空白区域编写代码。

程序参考运行效果图如下:

1
2
3
4
5
6
7
我是使用无参构造产生的猴子:
名称:长尾猴
特征:尾巴长
============================
我是使用带参构造产生的猴子:
名称:白头叶猴
名称:头上有白毛,喜欢吃树叶

任务

1、创建Monkey类

​ 属性:名称(name)和特征(feature)

​ 方法:

​ 1) 无参构造方法(默认初始化 name 和 feature 的属性值,属性值参考效果图)

​ 2) 带参构造方法,接收外部传入的参数,分别向 name 和 feature 赋值

2、创建测试类

​ 分别通过无参构造方法和带参构造方法,完成对象实例化实例化对象,并打印输出对象信息,输出格式如效果图。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Monkey {
//属性:姓名(name)、特征(feature)
String name;
String feature;

//无参的构造方法(默认初始化name和feature的属性值,属性值参考效果图)
public Monkey(){

}

public Monkey(String name,String feature){
this.name=name;
this.feature=feature;
}

//带参的构造方法(接收外部传入的参数,分别向 name 和 feature 赋值)

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Test {

public static void main(String[] args) {
Monkey one=new Monkey();
one.name="长尾猴";
one.feature="尾巴长";
//调用无参构造方法实例对象

System.out.println("我是使用无参构造产生的猴子:");
System.out.println("名称:"+one.name);
System.out.println("特征:"+one.feature);
System.out.println("============================");
//打印输出对象属性

Monkey two=new Monkey("白头叶猴","头上有白毛,喜欢吃树叶");
//调用带参构造方法实例对象

System.out.println("我是使用带参构造产生的猴子:");
System.out.println("名称:"+two.name);
System.out.println("名称:"+two.feature);
//打印输出对象属性

}

}
-------------本文结束感谢您的阅读-------------