一、继承中成员变量的访问特点:
打印结果为:zishow
这种情况打印出来的结果是Zi
这种情况打印的是Fu
这种情况就会报错
对于重名的情况,没有关键字,那么就是就近原则,打印出的是ziShow;
this.name 指的是Zi(在本类的成员变量去找)
super.name 指的是父类中的Fu;
代码:
代码结果:
案例:
二、继承中成员方法访问特点:
案例:
public class test{
public static void main(String[] args) {
overseaStudent s = new overseaStudent();
s.lunch();
}
}
class Person{
public void eat(){
System.out.println("吃菜,吃米饭");
}
public void drink(){
System.out.println("喝开水");
}
}
class overseaStudent extends Person{
public void lunch(){
this.eat();
this.drink();
super.eat();
super.drink();
}
public void eat(){
System.out.println("吃意大利面");
}
public void drink(){
System.out.println("喝冰美式");
}
}
运行结果为:
因为this是就近原则,super直接去父类找
三、方法的重写:
下面涉及到了重写,需要加上@override;
public class test{
public static void main(String[] args) {
overseaStudent s = new overseaStudent();
s.lunch();
}
}
class Person{
public void eat(){
System.out.println("吃菜,吃米饭");
}
public void drink(){
System.out.println("喝开水");
}
}
class overseaStudent extends Person{
public void lunch(){
this.eat();
this.drink();
super.eat();
super.drink();
}
@Override
public void eat(){
System.out.println("吃意大利面");
}
@Override
public void drink(){
System.out.println("喝冰美式");
}
}
调用的是A的虚方法表里的method 1,和覆盖的method 2;
调用的是B的虚方法表里的method 1,和覆盖的method 2;
代码案例:
画图分析:
test类
public class test{
public static void main(String[] args) {
hashiqi h = new hashiqi();
h.eat();
h.drink();
h.lookHome();
h.breakHome();
shapi s = new shapi();
s.eat();
s.drink();
s.lookHome();
tianyuan t = new tianyuan();
t.eat();
t.drink();
t.lookHome();
}
}
class dog{
public void eat(){
System.out.println("狗吃狗粮");
}
public void drink(){
System.out.println("狗喝水");
}
public void lookHome(){
System.out.println("狗在看家");
}
}
hashiqi 类:
public class hashiqi extends dog{
public void breakHome(){
System.out.println("哈士奇在拆家");
}
}
shapi 类:
public class shapi extends dog{
@Override
public void eat(){
super.eat();
System.out.println("沙皮狗在吃骨头");
}
}
tianyuan 类:
public class tianyuan extends dog{
@Override
public void eat(){
System.out.println("中华田园犬吃剩饭");
}
}
代码运行结果: