【问题标题】:Use of keyword 'this'使用关键字“this”
【发布时间】:2013-06-01 12:00:52
【问题描述】:

我很难理解在超类构造函数中使用“this”时如何准确计算出它所指的内容。

我有三个班级:

     public class Animal {

        public int x;

        public Animal() {
            this.x++;
            System.out.println(this);
            System.out.println(this.x);
            System.out.println();
        }

        public String toString() {
            return "Animal";
        }
    }

public class Mammal extends Animal{

    public int x;

    public Mammal() {
        this.x++;
        System.out.println(this);
        System.out.println(this.x);
        System.out.println();
    }

    public String toString() {
        return "Mammal";
    }

}

public class Dog extends Mammal{
    public int x;

    public Dog() {
        this.x++;
        System.out.println(this);
        System.out.println(this.x);
        System.out.println();
    }

    public String toString() {
        return "Dog " + x;
    }

    public static void main(String[] args) {
        Dog rover = new Dog();
    }

}

调用Dog构造函数的结果是:

狗 0 1

狗 0 1

狗 1 1

所以当我在 Animal 构造函数中调用 this.toString() 时,this 指的是 rover(狗)。但是当我在 Animal 构造函数中执行 this.x++ 时,它在 Animal 中而不是在 Dog 中增加 x。

正确吗?为什么 this.x++ 不增加流动站的 x?

【问题讨论】:

    标签: java inheritance polymorphism


    【解决方案1】:

    通过在 Animal 的子类中声明变量 x,您实际上是在遮蔽 Animal 的变量 x,所以 Mammal 中的 this.x 指的是 Mammal 中的 x,它遮蔽了 Animal 的 x。当然,在 Animal 构造函数中,x 指的是 Animal 中的 x,因为 Animal 类不知道任何子类。

    我不知道您为什么要隐藏 x,删除 Animal 的所有子类中的 public int x 应该会导致您期望的行为。然后,Animal 的所有子类将引用在 Animal 中声明的 x。

    更多关于阴影的详细信息可以在这里找到: http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15

    希望我能帮上忙

    【讨论】:

      【解决方案2】:

      在实例方法或构造函数中,this 是对当前对象的引用——正在调用其方法或构造函数的对象。您可以使用 this 从实例方法或构造函数中引用当前对象的任何成员。

      它对于区分实例变量和局部变量(包括参数)很有用,但它本身可以用来简单地引用成员变量和方法,调用其他构造函数重载,或者简单地引用实例。

      【讨论】:

      • 但我认为在这种情况下当前对象将是流动站?那么 this.x 怎么不是指漫游者的 x 呢?
      【解决方案3】:

      当您在super classsub class 中都有x 时,您有this.x。子类中的引用this.x 指的是子类中的变量,而不是超类中的变量。这很直观,因为您正在扩展超类以根据需要对其进行修改,并且在 OOP 中,通常会编写子类重新声明(我的意思是声明具有相同名称的变量以进行自定义或类似的东西)一些变量。如果您想要来自super class 的变量或方法,尤其是您的服务中总是有super 关键字。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-10
        • 1970-01-01
        • 2019-11-18
        • 2018-09-19
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        相关资源
        最近更新 更多