其实这个我最近想明白了,是因为遇到了一段预测失败的代码很简单哈
首先 重载 和 重写是不同的,哪里不同这里不说,留到另外的日志。
首先看这个代码,这里面只有重载没有重写:
01
public
class
testInter
{
02
03
public
static
void
main
(
String
[]
args
)
{
04
A
a
=
new
B();
05
B b
=
new
B();
06
a
.
m
(
5
);
07
//a.m(1.1);
08
b
.
m
(
1
);
09
b
.
m
(
1.1
);
10
}
11
}
12
13
class
A
{
14
protected
int
i
;
15
public
void
m
(
int
i
)
16
{
17
this
.
i
=
i
;
18
System
.
out
.
println
(
“
A
”
+
this
.
i
);
19
}
20
}
21
22
class
B
extends
A
23
{
24
double
d
;
25
public
void
m
(
double
d
)
26
{
27
this
.
d
=
d
;
28
System
.
out
.
println
(
“
B
”
+
this
.
d
);
29
}
30
}
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
这里我第一个是用父类引用指向子类对象,第二个就是普通的直接实例化B;
他的输出
A5
B1
B1.1
中间我注释掉了a.m(1.1)是因为它会报错,为什么?因为对于a来说它只能调用m(int i)也就是说只能调用父类的方法,除非它被重写(这就是其中重要的不同)。
同样我把代码改下:
01
public
class
testInter
{
02
03
public
static
void
main
(
String
[]
args
)
{
04
A
a
=
new
B();
05
B b
=
new
B();
06
a
.
m
(
1
);
07
b
.
m
(
2
);
08
}
09
10
}
11
12
class
A
{
13
protected
int
i
;
14
public
void
m
(
int
i
)
15
{
16
this
.
i
=
i
;
17
System
.
out
.
println
(
"AAA"
);
18
}
19
}
20
21
class
B
extends
A
22
{
23
double
d
;
24
public
void
m
(
int
d
)
25
{
26
this
.
d
=
d
;
27
System
.
out
.
println
(
"BBB"
);
28
}
29
}
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
看,这次m方法是被重写了,那么输出是什么?
BBB
BBB
这就是结果,所以呢,很简单了,看到调用的方法,千万别乱了~~
有错误之处,请指出,谢谢~