我是靠谱客的博主 俊逸鼠标,这篇文章主要介绍《Java基础——构造器(构造方法)》Java基础——构造器(构造方法),现在分享给大家,希望可以做个参考。

Java基础——构造器(构造方法)

        

        

        

总结:


1.构造器名应与类名相同,且无返回值。

2."new 方法"的本质就是在调用构造器。

3.构造器的作用——初始化对象的值。

        

        

一、无参构造;


规则:

1.无参构造的作用是:实例化一个对象。

2.即使不定义构造器,也会默认生成无参构造。

        

格式:

复制代码
1
2
3
4
5
6
7
8
9
10
class 类名 { int 字段名; String 字段名; public 类名() { this.字段名="待输出的值"; //输出“待输出的值”; } }

例如:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
class Student { String name; public Student() { this.name="苏巴提"; } public static void main(String[] args) { Student m=new Student(); System.out.println(m.name); } }

编译结果:

复制代码
1
苏巴提

        

        

二、有参构造;


规则:

1.有参构造的作用是:初始化类中的属性。

2.使用有参构造前必须手动创建一个无参构造。

3.“new 方法”后面的参数类型、个数与有参构造相对应时才能调用。

4.有参构造的优先级别高于无参构造。

        

格式:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class 类名 { String 字段名1; int 字段名2; public 类名() { } public 类名(String 字段名3, int 字段名4) { this.字段名1=字段名3; //输出“new 方法”中的参数; this.字段名2=6; //输出“6”; } }

例如:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Student { String name; int num; public Student() { this.name="苏巴提"; } public Student(String name, int num) { this.name=name; this.num=6; } public static void main(String[] args) { Student m=new Student("努尔居力", 7); System.out.println(m.name); System.out.println(m.num); } }

编译结果:

复制代码
1
2
努尔居力 6

最后

以上就是俊逸鼠标最近收集整理的关于《Java基础——构造器(构造方法)》Java基础——构造器(构造方法)的全部内容,更多相关《Java基础——构造器(构造方法)》Java基础——构造器(构造方法)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部