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
父类引用可指向子类对象,但此时调用的是子类函数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律