1 多态 & 虚方法调用
public class TestVirtualInvoke {
void doStuff(Shape s) {
s.draw();
}
public static void main(String[] args) {
Circle c = new Circle();
Triangle t = new Triangle();
Line l = new Line();
doStuff(c);
doStuff(t);
doStuff(l);
}
}
class Shape {
void draw() { System.out.println("Shape Drawing"); }
}
class Circle extends Shape {
void draw() { System.out.println("Draw Circle"); }
}
class Triangle extends Shape {
void draw() { System.out.println("Draw Three Lines"); }
}
class Line extends Shape {
void draw() { System.out.println("Draw Line"); }
}
// 输出结果
// Draw Circle
// Draw Three Lines
// Draw Line
Java 中的 **instanceof
** 关键词可以判断改对象是不是某个对象的实例:
Object[] things = new Object[3];
things[0] = new Integer(4);
things[1] = new Double(3.14);
things[2] = new String("2.09");
double res = 0;
for (int i = 0; i < things.length; ++i) {
if (things[i] instanceof Integer)
res += things[i].intValue();
else if (things[i] instanceof Double)
res += thing[i].doubleValue();
}
2 非虚方法
class JavaP3Methods {
void fun();
private void p() {}
static void s() {}
public static void main(String[] args) {
JavaP3Methods obj = new JavaP3Methods();
obj.fun();
obj.p();
obj.s();
}
}
其汇编代码为:
invokevirtual #4
invokespecial #5
invokestatic #7