
用法
1、程序在编译的时候调用的其实是父类的eat方法,但是在运行时运行的则是子类的eat方法,运行期间发生了绑定。
2、使用前题,先向上转型,通过父类引用来调用父类和子类同名的覆盖方法
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package chapeter04;
class Test
{
public Test() { }
public void setName(String n)
{
this .name=n;
System.out.println( "在父类中" );
}
public String getName()
{
return this .name;
}
private String name;
}
public class Sample4_12 extends Test
{
public void setArea(String a)
{
this .area=a;
}
public String getArea()
{
return this .area;
}
public static void main(String[] args)
{
Sample4_12 child = new Sample4_12();
Test test []= new Test[2];
test[0]=child;
test[0].setName( "silence" );
test[1]= new Test();
}
private String area;
}
|
以上就是java动态绑定的使用,大家在开始使用前,需要对其的使用前提进行明确。更多Java学习指路:Java基础
本教程操作环境:windows7系统、java10版,DELL G3电脑。