当前页面: 开发资料首页 → J2SE 专题 → 多态性
多态性
摘要: 多态性
谁能给举个多态例子!!讲解下!!!
即动态绑定,假设Father类是Son类的父类
Father f = new Son()
然后用f调用方法,这样调用的是子类的方法
除非子类没有该方法则调用父类的,或者父类该方法在
父类声明为private或final也会调用父类的
其余情况调用子类的
跟C++的virtual一样
class Father
{
int age = 10;
Father(int a)
{
this.age = a;
if(this instanceof Son)
{
System.out.println("this is an instance of Son. ");
}
if(this instanceof Father)
{
System.out.println("this is an instance of Father. ");
}
print();
}
void print()
{
System.out.println("father:" + this.age);
}
}
class Son extends Father
{
int age = 20;
Son(int a)
{
super(a);
this.age = a;
if(this instanceof Son)
{
System.out.println("this is an instance of Son. ");
}
if(this instanceof Father)
{
System.out.println("this is an instance of Father. ");
}
print();
}
void print()
{
System.out.println("son:" + this.age);
}
}
class Test
{
public static void main(String[] args)
{
Son test = new Son(5);
test.print();
}
}
学习