Java基础补全 之 继承
JAVA基础特性:多态,继承,封装
本文补充完善一下继承的相关知识
基础类间的继承
-
子类对父类函数的重写(Override)
有参无参构造函数的继承调用
public class Heritage {
class A{
A(){
System.out.println("this is construct function of class A");
}
A(String param){
System.out.println("this is construct function with param of class A");
}
}
class B extends A{
B(){
System.out.println("this is construct function of class B");
}
B(String param){
System.out.println("this is construct function with param of class B");
}
}
public void test(){
B b = new B();
B bb = new B("fuck");
}
public static void main(String[] args) {
new Heritage().test();
}
}
this is construct function of class A
this is construct function of class B
this is construct function of class A
this is construct function with param of class B
实例化时,若不给定参数,编译器自动调用无参构造函数。此时创建子类对象,编译器先调用父类的无参构造函数,再调用子类的构造函数。
给定参数时,若不在子类构造函数用super指定父类构造函数,则默认调用父类无参构造函数,若想要调用父类相应的有参构造函数,则需要手动用super()函数在子类构造函数内调用。
super
B(String param){
super(param);
System.out.println("this is construct function with param of class B");
}
this is construct function with param of class A
this is construct function with param of class B
-
子类父类构造函数间的调用关系
public class Heritage {
class A{
A(){
System.out.println("this is construct function of class A");
}
A(String param){
System.out.println("this is construct function with param of class A");
}
void display(){
System.out.println("this is function of class A");
}
}
class B extends A{
B(){
System.out.println("this is construct function of class B");
}
B(String param){
super(param);
System.out.println("this is construct function with param of class B");
}
@Override
void display(){
System.out.println("this is function of class B");
}
}
public void test(){
// B b = new B();
// B b1 = new B("fuck");
A b2 = new B();
b2.display();
}
public static void main(String[] args) {
new Heritage().test();
}
}
this is construct function of class A
this is construct function of class B
this is function of class B
父类引用可指向子类对象,但此时调用的是子类函数