虚方法的调用
package w5;
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);//调用的是虚方法,根据实际对象来调用,是Circle里的方法而不是Shape!
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
*/
非虚方法的调用
package w5;
class TestStaticInvoke
{
public static void main( String [] args ){
Circle c = new Circle();
Triangle t = new Triangle();
Line l = new Line();
doStuff(c);//Circle是Shape的子类,c仍可以作为doStuff的参量,但由于doStuff是被static修饰的,所以draw()不存在虚化问题,仍然执行Shape.draw
doStuff(t);
doStuff(l);
Shape s = new Circle();
doStuff(s);
s.draw();
Circle c2 = new Circle();
c2.draw();
}
static void doStuff( Shape s ){//被static final private修饰的方法为非虚方法(不能被子类更改)
s.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*/