1.父類的構造方法是不會被子類繼承的,但是子類的構造方法中會有一個隱式的super()來調用父類中的無參數構造方法。
驗證代碼如下:
public class FatherClass {
int a;
int b;
public FatherClass() {
a = 10;
}
public FatherClass(int b) {
this.b = b;
}
public void getClassName(){
System.out.println("我是FatherClass");
}
}
public class Test extends FatherClass{
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.a);
System.out.println(t.b);
}
@Override
public void getClassName(){
System.out.println("我是Test");
}
}
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
執行Test類,輸出結果是10和0。
上面代碼在內存中的執行過程如下圖(我只畫了堆中的內存變化):
在這里插入圖片描述
2.如果子類調用了父類的有參構造方法,就不會再有隱式super()的調用父類的無參構造了
public class FatherClass {
int a;
int b;
public FatherClass() {
a = 10;
}
public FatherClass(int b) {
this.b = b;
}
}
1
2
3
4
5
6
7
8
9
10
public class Test extends FatherClass{
public Test(int b) {
super(b);
}
public static void main(String[] args) {
Test t = new Test(10);
System.out.println(t.a);
System.out.println(t.b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
輸出結果0和10
3.抽象類本身不能被實例化,但是可以有構造方法。
---------------------
作者:czx2018
來源:CSDN
原文:https://blog.csdn.net/czx2018/article/details/82852548
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!