Java关于父类引用指向子类对象

来源:互联网 发布:sql语句里case when 编辑:程序博客网 时间:2024/05/17 08:40

1. 首先, java的多态是指子类重写了父类的方法,在程序运行期间(非编译),根据引用指向的“实际对象”来调用对象的方法,子类是不能重写父类的变量的。

class Father{int age = 30;String name = "雷盼是父亲";public Father(String AName){System.out.println(Father.class.getName());}public Father(){System.out.println("Father Constructor!");}public int getAge(){return this.age;}public String getName(){return this.name;}};class Son extends Father{int age = 1;String name = "雷梓诺是儿子";public Son(){//super("12");//会隐式调用,不管你写不写superSystem.out.println(Son.class.getName());}public int getAge(){return this.age;}public String getName(){return this.name;}}class Extends {public static void main(String[] args) {Father f = new Son();//子类构造时必然会调用父类的构造方法先System.out.println(f.getName());//方法是在运行时动态绑定System.out.println(f.name);//属性是在编译时指定(不会知道father指向了谁)}}



0 0
原创粉丝点击