黑马程序员技术交流社区

标题: 一个关于继承的小问题 [打印本页]

作者: 天方夜谭    时间: 2014-7-12 08:11
标题: 一个关于继承的小问题
为什么说实际参数列表和形式列不同
public class Example{
   public static void main(String[] agrs){
   A a=new A();
System.out.println(a.f(1f,54f,3f));

  }
}
class A{
   int x,y;
   double f(float a,float b){
   
    return x+y;
   }
}
class B extends A{
   
double  f(float a,float b,float c){  //这不是覆盖吗

  return x+y;
  }
}
作者: hejinzhong    时间: 2014-7-12 13:42
  1. class  ExtendsDemo3
  2. {
  3. public static void main(String[] args)
  4. {
  5.   A a = new A();//你建立的是父类A的对象,A中没有f(a,b,c)这样的函数。
  6.                 //想调用子类中的方法,就要建立子类的对象,或者将父类向下转型。
  7.   System.out.println(a.f(1f,54f,3f));
  8. }
  9. }
  10. class A
  11. {
  12. int x,y;//定义这两个变量没有意义
  13. double f(float a,float b)
  14. {
  15.   return a+b;
  16. }
  17. }
  18. class B extends A
  19. {
  20. double f(float a,float b,float c)//这个是函数重载了,并没有覆写。
  21. {
  22.   return a+b+c;
  23. }
  24. }
  25. /*
  26. 继承后B类实际是:
  27. class B extends A
  28. {
  29. double f(float a,float b)
  30. {
  31.   return a+b;
  32. }
  33. double f(float a,float b,float c)//这个是函数重载了,并没有覆写。
  34. {
  35.   return a+b+c;
  36. }
  37. }
复制代码


作者: hejinzhong    时间: 2014-7-12 13:44
在你的A类中没有f(a,b,c)这样的函数。
作者: cat73    时间: 2014-7-12 13:50
你在测试类里貌似没创建B的实例,而且参数数量与类型不同,不会被覆盖,只会认为是重载




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2