super,this引用构造函数
来源:互联网 发布:淘宝上好看的卫衣店 编辑:程序博客网 时间:2024/05/21 17:08
3.引用构造函数
super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。
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
class
Person {
public
static
void
prt(String s) {
System.out.println(s);
}
Person() {
prt(
"父类·无参数构造方法: "
+
"A Person."
);
}
//构造方法(1)
Person(String name) {
prt(
"父类·含一个参数的构造方法: "
+
"A person's name is "
+ name);
}
//构造方法(2)
}
public
class
Chinese
extends
Person {
Chinese() {
super
();
// 调用父类构造方法(1)
prt(
"子类·调用父类”无参数构造方法“: "
+
"A chinese coder."
);
}
Chinese(String name) {
super
(name);
// 调用父类具有相同形参的构造方法(2)
prt(
"子类·调用父类”含一个参数的构造方法“: "
+
"his name is "
+ name);
}
Chinese(String name,
int
age) {
this
(name);
// 调用具有相同形参的构造方法(3)
prt(
"子类:调用子类具有相同形参的构造方法:his age is "
+ age);
}
public
static
void
main(String[] args) {
Chinese cn =
new
Chinese();
cn =
new
Chinese(
"codersai"
);
cn =
new
Chinese(
"codersai"
,
18
);
}
}
运行结果:
父类·无参数构造方法: A Person.
子类·调用父类”无参数构造方法“: A chinese coder.
父类·含一个参数的构造方法: A person's name is codersai
子类·调用父类”含一个参数的构造方法“: his name is codersai
父类·含一个参数的构造方法: A person's name is codersai
子类·调用父类”含一个参数的构造方法“: his name is codersai
子类:调用子类具有相同形参的构造方法:his age is 18
从本例可以看到,可以用super和this分别调用父类的构造方法和本类中其他形式的构造方法。
例子中Chinese类第三种构造方法调用的是本类中第二种构造方法,而第二种构造方法是调用父类的,因此也要先调用父类的构造方法,再调用本类中第二种,最后是重写第三种构造方法。
阅读全文
0 0
- super,this引用构造函数
- 构造函数,super,this
- super() this() super this 与构造函数
- 构造,super,this
- 构造方法,super,this
- JAVA学习,this(),super()调用构造函数研究
- 构造函数的this和super的调用
- 子父类构造函数的调用演示,区分this()和super()
- JAVA中super和this调用构造函数
- Java - 构造函数、this 和 super的使用
- this super 构造函数 以及 加载及调用顺序
- [java]构造方法super() this()
- 为什么java构造函数的构造器只能在第一行写this() super()
- this用法-当前对象的引用与调用构造函数
- 继承、多态——成员变量、成员函数、构造函数(this、super)
- 黑马程序员——java基础之构造函数、this、super、static
- 为什么super(...)和this(...)只能在构造函数中的第一句出现?
- java中this()和super()在子类构造函数中不能共存的原因
- Centos6.5安装epel
- 输入一个大数将其转化为二进制输出
- linux进阶之旅(三)& heartbeat实现高可用
- C 语言运算符优先级(记忆口诀)
- Servlet 服务器端编程
- super,this引用构造函数
- 9.26日常总结
- MySQL基本操作语法
- 欢迎使用CSDN-markdown编辑器
- 数据结构实验之栈与队列九:行编辑器
- dubbo 基本概念
- 第四周项目4猴子选大王
- const常量与define宏定义的区别
- php培训学习记录 第四天