1.子类可以调用父类的属性和方法(private修饰的不可以调用),当子类和父类有同名的属性时,通过用this.属性和super.属性进行区分
2.通过子类的构造器创建子类的实例化对象时,会默认调用父类的构造器,即super()
3.子类重写了父类的方法A,那么当子类的实例化对象调用方法A时,调用的是子类的重写的方法
4.测试的代码块如下,可以自行修改,测试自己想要的场景输出结果
父类
public class Father {
private String money;
public int age = 50;
public Father() {
System.out.println("这是父类的构造器");
}
public void work(){
System.out.println("这是父类的work方法");
}
public void eat(){
System.out.println("这是父类的eat方法");
}
private void smoking(){
System.out.println("这是父类的work方法");
}
}
子类
public class Son extends Father {
public int score;
public Son(int score) {
super();
this.score = score;
System.out.println("这是子类的构造器");
}
public void eat(){
System.out.println("这是子类重写的eat方法");
}
public void study() {
int myAge = age;//调用父类的属性
System.out.println("这是子类的study方法");
System.out.println("这是子类调用父类的age属性,age=" + myAge);
}
public void play(){
work();//调用父类的方法
System.out.println("这是子类的play方法");
}
}
测试类
public class ExtendsTest {
public static void main(String[] args) {
Son son = new Son(90);
son.play();
son.eat();
System.out.println(son.age);
}
}
运行结果
这是父类的构造器
这是子类的构造器
这是父类的work方法
这是子类的play方法
这是子类重写的eat方法
50