1.虚拟方法调用也叫动态绑定
2.具体是什么用代码来说明
Person类
1 package com.alibaba.com.miao; 2 3 public class Person { 4 5 protected String name; 6 protected int age; 7 8 public String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 public int getAge() { 17 return age; 18 } 19 20 public void setAge(int age) { 21 this.age = age; 22 } 23 24 public Person(String name, int age) { 25 super(); 26 this.name = name; 27 this.age = age; 28 } 29 30 public Person() { 31 32 } 33 34 public String getInfo() { 35 return "Person [name=" + name + ", age=" + age + "]"; 36 } 37 38 }
Student类继承Person类
1 package com.alibaba.com.miao; 2 3 public class Student extends Person { 4 public String getInfo() { 5 return "Student [name=" + name + ", age=" + age + "]"; 6 } 7 }
Test测试类
1 package com.alibaba.com.miao; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 //没有使用虚拟方法调用 7 Person p = new Person(); 8 p.setAge(20); 9 p.setName("super hacker"); 10 System.out.println(p.getInfo()); 11 12 Student stu = new Student(); 13 stu.setAge(21); 14 stu.setName("geek"); 15 System.out.println(stu.getInfo()); 16 //使用虚拟方法调用 17 Person p1 = new Student(); 18 p1.setAge(19); 19 p1.setName("me"); 20 System.out.println(p1.getInfo()); 21 } 22 }
由此可见:
编译时p1为Person类型,而方法的调用是在运行时确定的,所以调用的是Student类的getInfo()方法。
这样做的好处可以降低类之间的耦合性。
虚拟方法调用--在多态下使用