关于Java继承中的this的表示关系

avatar 2020年01月12日12:03:13 6 2062 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此
今早有个朋友在群里问了一个问题,关于继承的 this 问题,他不是很理解,我们先发题。

其主要是对两种情况的输出结果不理解。

问题如下


1.情况一
  1. public class Father {
  2.     int age;
  3.     public Father() {
  4.         this.age = 40;
  5.     }
  6.     void eat() {
  7.         System.out.println("父亲在吃饭");
  8.     }
  9. }
  10. public class Child extends Father {
  11.     public Child() {
  12.         this.age = 18;
  13.     }
  14.     void eat() {
  15.         System.out.println("孩子在吃饭");
  16.     }
  17.     public static void main(String[] args) {
  18.         Father father = new Child();
  19.         System.out.println(father.age); // 18
  20.         father.eat(); // 孩子在吃饭
  21.     }
  22. }

输出结果:
18
孩子在吃饭



2.情况二
  1. public class Father {
  2.     int age;
  3.     public Father() {
  4.         this.age = 40;
  5.     }
  6.     void eat() {
  7.         System.out.println("父亲在吃饭");
  8.     }
  9. }
  10. public class Child extends Father {
  11.     int age;
  12.     public Child() {
  13.         this.age = 18;
  14.     }
  15.     void eat() {
  16.         System.out.println("孩子在吃饭");
  17.     }
  18.     public static void main(String[] args) {
  19.         Father father = new Child();
  20.         System.out.println(father.age); // 40
  21.         father.eat(); // 孩子在吃饭
  22.     }
  23. }

输出结果:

40
孩子在吃饭



这两种情况唯一的区别就是情况二中 子类有一个和父类相同的属性


解答


对于子类和父类同名成员变量,调用该变量,将直接获取父类的属性

因为 Java 的重写,只有对方法的重写,对属性并不存在重写。

举例
  1. Father father = new Child();
  2. father.setAge(11);
  3. System.out.println(father.age);

我们给子类和父类都添加 getter/setter 方法,然后这里在第二行加 setAge

当我们都以为这个 father.age 最终输出为 11 时,结果大跌眼镜,输出结果为 40。

也就是说这里通过 . 获得成员变量值时,获得的是父类同名变量的值。



如果我们想获得子类的对象值,通过 get 方法,返回子类对象的成员变量即可

完整示例如下
  1. public class Child extends Father {
  2.     int age;
  3.     public Child() {
  4.         this.age = 18;
  5.     }
  6.     void eat() {
  7.         System.out.println("孩子在吃饭");
  8.     }
  9.     @Override
  10.     public int getAge() {
  11.         return age;
  12.     }
  13.     @Override
  14.     public void setAge(int age) {
  15.         this.age = age;
  16.     }
  17.     public static void main(String[] args) {
  18.         Father father = new Child();
  19.         father.setAge(11);
  20.         System.out.println(father.age); // 40
  21.         System.out.println(father.getAge()); // 11
  22.         father.eat(); // 孩子在吃饭
  23.     }
  24. }

输出结果:

40
11
孩子在吃饭

  • 微信
  • 交流学习,服务定制
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0