java动态绑定方法怎么用

其他教程   发布日期:2025年03月23日   浏览次数:99

本篇内容介绍了“java动态绑定方法怎么用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

用法

1、程序在编译的时候调用的其实是父类的eat方法,但是在运行时运行的则是子类的eat方法,运行期间发生了绑定。

2、使用前题,先向上转型,通过父类引用来调用父类和子类同名的覆盖方法

实例

  1. package chapeter04;
  2. class Test
  3. {
  4. public Test() { }
  5. public void setName(String n)
  6. {
  7. this.name=n;
  8. System.out.println("在父类中");
  9. }
  10. public String getName()
  11. {
  12. return this.name;
  13. }
  14. private String name;
  15. }
  16. public class Sample4_12 extends Test
  17. {
  18. public void setArea(String a)
  19. {
  20. this.area=a;
  21. }
  22. public String getArea()
  23. {
  24. return this.area;
  25. }
  26. public static void main(String[] args)
  27. {
  28. // TODO Auto-generated method stub
  29. Sample4_12 child = new Sample4_12();
  30. Test test []=new Test[2];
  31. test[0]=child;
  32. test[0].setName("silence");
  33. test[1]=new Test();
  34. }
  35. private String area;
  36. }

以上就是java动态绑定方法怎么用的详细内容,更多关于java动态绑定方法怎么用的资料请关注九品源码其它相关文章!