class TestStaticInvoke
{
static 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);
Shape s = new Circle();
doStuff(s);
s.draw();
Circle c2 = new Circle();
c2.draw();
}
}
class Shape
{
static void draw(){ System.out.println("Shape Drawing"); }
}
class Circle extends Shape
{
static void draw(){ System.out.println("Draw Circle"); }
}
class Triangle extends Shape
{
static void draw(){ System.out.println("Draw Three Lines"); }
}
class Line extends Shape
{
static void draw(){ System.out.println("Draw Line"); }
}
运行结果:
Shape Drawing
Shape Drawing
Shape Drawing
Shape Drawing
Shape Drawing
Draw Circle
请按任意键继续.
class TestVirtualInvoke
{
static 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
请按任意键继续. . .
结论,
static方法不存在调用虚方法,在编译时就被设定为invokestatic,他的引用只和声明对象有关,与实例无关。