父类引用指向子类对象
声明为父类 实际创建子类对象
person student = new student();
student 调用的属性是父类中的属性,如果子类重写了父类方法,调用的是子类方法。
例如
person类
/** * @author 林俊伟 * @create 2021-09-02 9:27 */ public class person { int age=15; public person() { System.out.println("调用父类构造方法"); } public void test(){ System.out.println("父类的"); } }
student类
/** * @author 林俊伟 * @create 2021-09-02 9:28 */ public class student extends person{ int age=30; String per = "我是学生"; public void person(int age){ } public student(){ super(); System.out.println("我是一个学生"); } public void test(){ System.out.println("子类的"); } public void test1(){ System.out.println("子类特有的的"); } }
test主函数
/** * @author 林俊伟 * @create 2021-09-02 8:58 */ public class test { public static void main(String[] args) { person student = new student(); //这个调用的是父类的属性 System.out.println(student.age); student.test(); System.out.println(student.getClass()); //如果要调用子类有而父类无的方法和属性时,需要强制转换 System.out.println(((student)student).per); ((student) student).test1(); } }
这种使用有什么好处吗?
百度说是多态和解耦,不理解
今天看了深入理解jvm
声明时为 person 类型 是 静态类型 在编译时确定的
实际创建 student 类型 是实际类型 是运行时确定的
声明的是父类,编译时用的就是父类,运行时调用的子类的方法,属性age是在编译时的写入常量池了,所以用的的父类的
感觉理解还是有问题