A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 大手牵小手 中级黑马   /  2015-3-3 21:15  /  781 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class A
  2. {
  3.         public double y=11.456789;
  4.         public void f()
  5.         {
  6.                 y=y+1;
  7.                 System.out.printf("y=%f\n",y);
  8.         }
  9. }

  10. class B extends A
  11. {
  12.         int y = 0;
  13.         public void g()
  14.         {
  15.                 y=y+100;
  16.                 System.out.printf("y=%d\n",y);
  17.         }
  18. }
  19. public class Example {

  20.         public static void main(String[] args) {
  21.                 // TODO Auto-generated method stub
  22.                 B b =new B();
  23.                 b.y = 200;
  24.                 b.g();
  25.                 b.f();
  26.         }

  27. }
复制代码

不懂b.f()的值,求解

4 个回复

倒序浏览
好歹给类跟变量起个好理解,好记的名字
回复 使用道具 举报
  1. class A
  2. {
  3.         public double y=11.456789;
  4.         public void f()
  5.         {
  6.                 this.y=this.y+1;
  7.                 System.out.printf("y=%f\n",this.y);
  8.         }
  9. }
  10. //相当于
  11. class B extends A
  12. {
  13.         int y = 0;
  14.         public void g()
  15.         {
  16.                 this.y=this.y+100;
  17.                 System.out.printf("y=%d\n",y);
  18.         }
  19.         //相当于子类中有这样的方法,继承过来的
  20.    public void f()
  21.   {
  22.       super.y=super.y+1;
  23.       System.out.printf("y=%f\n",super.y);
  24.   }
  25. }
  26. public class Example {

  27.         public static void main(String[] args) {
  28.                 // TODO Auto-generated method stub
  29.                 B b =new B();
  30.                 b.y = 200;
  31.                 b.g();
  32.                 b.f();
  33.         }
复制代码



回复 使用道具 举报
本帖最后由 wdhm5423 于 2015-3-3 23:00 编辑

在继承的时候,允许子类存在与父类同名的成员变量,但是并不覆盖父类的成员变量,他们同时存在。就近原则。
b.y=200 就近调用子类的 y =200(b是子类)
b.g()  g方法就近调用子类的y(g在子类中)
b.f()  f方法就近调用父类的y(f在父类中)


回复 使用道具 举报
wdhm5423 发表于 2015-3-3 22:57
在继承的时候,允许子类存在与父类同名的成员变量,但是并不覆盖父类的成员变量,他们同时存在。就近原则。 ...

我懂了!三克油!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马