多态是父类的引用指向了自己的子类对象。
当调用方法时,会根据实际的对象去调用方法
总结:变量在编译阶段绑定,方法在运行阶段绑定。属性不能重写,方法可以重写。
public class Father { public void method() { System.out.println("父类方法,对象类型:" + this.getClass()); } }
public class Son extends Father { public void method() { System.out.println("子类方法,对象类型:" + this.getClass()); } public static void main(String[] args) { Father sample = new Son();//向上转型 sample.method(); } }
父类和子类有相同的属性时
public class Person { public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class Student extends Person { public String name; public String getName() { return name; } public Student(String name) { this.name = name; super.name = "wangwu"; } public static void main(String[] args) { Person person = new Student("zhangsan"); System.out.println(person.name); //wangwu System.out.println("****************"); Student student_1 = new Student("zhangsan"); Person person_1 = student_1; System.out.println("person_1.getName() :" + person_1.getName()); //zhangsan System.out.println("person_1.name :"+ person_1.name); //wangwu System.out.println("student_1.getName() :" + student_1.getName());//zhangsan System.out.println("student_1.name :" + student_1.name);//zhangsan } }