class A
{
public void func1()
{
System.out.println("A func1 is calling");
}
public void func2()
{
func1();
}
}
class B extends A
{
public void func1()
{
System.out.println("B fun1 is calling");
}
}
class C
{
public static void main(String [] args)
{
B b=new B();
A a=b;
callA(a);
callA(new B());
}
public static void callA(A a)
{
a.func1();
a.func2();
}
}
运行结果:
D:\>javac C.java
D:\>java C
B fun1 is calling
B fun1 is calling
B fun1 is calling
B fun1 is calling
简单来说,就是RTTI,动态类型判定,也就是
B b=new B();
A a=new B();
只要等号右边类型是什么类型,而且已经覆盖父类的方法,那么调用该方法时,会自动知道相应的B中的覆盖方法。这是一定的,运行时多态。
==================================================
只对方法进行动态判定,属性的取值看,等号左边,也就是编译时类型。
将A和B添加一个属性,在索取值,看结果:
class A
{
public String name = "A CLASS";
public void func1()
{
System.out.println("A func1 is calling");
}
public void func2()
{
func1();
}
}
class B extends A
{
public String name = "B CLASS";
public void func1()
{
System.out.println("B fun1 is calling");
}
}
public class C
{
public static void main(String [] args)
{
B b=new B();
A a=b;
callA(a);
callA(new B());
System.out.println(a.name);
System.out.println(b.name);
System.out.println(new B().name);
}
public static void callA(A a)
{
a.func1();
a.func2();
}
}
运行结果:
D:\>javac C.java
D:\>java C
B fun1 is calling
B fun1 is calling
B fun1 is calling
B fun1 is calling
A CLASS
B CLASS
B CLASS
posted on 2007-01-05 09:53
坏男孩 阅读(784)
评论(0) 编辑 收藏 所属分类:
java命令学习