关于继承的例子
继承是再普通不过的概念,但是你真的能玩的转吗?
父类Person
public class Person {public void getName(){System.out.println("person name");}public void getPersonAge(){System.out.println("person age");}}子类Student
public class Student extends Person {public void getName(){System.out.println("student name");}public void getStudentAge(){System.out.println("student age");}}测试类Test
public class Test{public static void main(String[] args){Person p = new Student();p.getName();//输出student name,方法覆盖((Person)p).getName();//注意这个也输出student name,覆盖的很彻底p.getPersonAge();//输出person age //以上三个方法说明了一点:这个p引用的是一个实实在在的Student对象 //在这个对象中会包含父类的非私有方法以及未被覆盖的方法 //其实父类中的这个被覆盖的方法也不是完全不能访问到,做法是在Student类中调用super.getName() //有了以上这些概念之后,想一下下面这条语句如果p不进行强制类型转换的话为什么不能编译通过? //原因在于p是Person类型的引用,它无法调用getStudentAge()这个方法((Student) p).getStudentAge();//student age}}