1.显式调用父类的构造函数,因为父类没有无参构造函数,所有子类在继承的时候必须显式调用父类的构造函数来初始化父类。
class Parent {
int num;
Parent(int n) {
num = n;
System.out.println("Parent constructor called.");
}
}
class Child extends Parent {
String name;
Child(int n, String s) {
super(n); // 显式调用父类的有参构造函数
name = s;
System.out.println("Child constructor called.");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(5, "Tom");
}
}
2.访问父类的成员变量、方法
class Parent {
int num = 10;
}
class Child extends Parent {
int num = 20;
void printNum() {
System.out.println("Child's num: " + num);
System.out.println("Parent's num: " + super.num);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.printNum();
}
}
3.在重写方法中调用父类方法并实现增强
class Parent {
void doSomething() {
System.out.println("Parent is doing something.");
}
}
class Child extends Parent {
@Override
void doSomething() {
super.doSomething();
System.out.println("Child is doing something more.");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.doSomething();
}
}

3万+

被折叠的 条评论
为什么被折叠?



