1 多态 & 虚方法调用

image.png

image.png

  1. public class TestVirtualInvoke {
  2. void doStuff(Shape s) {
  3. s.draw();
  4. }
  5. public static void main(String[] args) {
  6. Circle c = new Circle();
  7. Triangle t = new Triangle();
  8. Line l = new Line();
  9. doStuff(c);
  10. doStuff(t);
  11. doStuff(l);
  12. }
  13. }
  14. class Shape {
  15. void draw() { System.out.println("Shape Drawing"); }
  16. }
  17. class Circle extends Shape {
  18. void draw() { System.out.println("Draw Circle"); }
  19. }
  20. class Triangle extends Shape {
  21. void draw() { System.out.println("Draw Three Lines"); }
  22. }
  23. class Line extends Shape {
  24. void draw() { System.out.println("Draw Line"); }
  25. }
  26. // 输出结果
  27. // Draw Circle
  28. // Draw Three Lines
  29. // Draw Line

Java 中的 **instanceof** 关键词可以判断改对象是不是某个对象的实例

  1. Object[] things = new Object[3];
  2. things[0] = new Integer(4);
  3. things[1] = new Double(3.14);
  4. things[2] = new String("2.09");
  5. double res = 0;
  6. for (int i = 0; i < things.length; ++i) {
  7. if (things[i] instanceof Integer)
  8. res += things[i].intValue();
  9. else if (things[i] instanceof Double)
  10. res += thing[i].doubleValue();
  11. }

2 非虚方法

image.png

  1. class JavaP3Methods {
  2. void fun();
  3. private void p() {}
  4. static void s() {}
  5. public static void main(String[] args) {
  6. JavaP3Methods obj = new JavaP3Methods();
  7. obj.fun();
  8. obj.p();
  9. obj.s();
  10. }
  11. }

其汇编代码为:

  1. invokevirtual #4
  2. invokespecial #5
  3. invokestatic #7

2.1 三种非虚的方法

image.png