Java继承和this关键字

标签 java this keyword

看看这段代码

public class Machine {
    public String name = "Machine";
    public static int j = 5;

    public void run() {
        System.out.println("Machine is running");
        System.out.println(this.name);
    }

    public void run2() {
        System.out.println("Machine is running");

        System.out.println(this.name);
        this.run();
    }
}

public class Computer extends Machine {
    String name = "Computer ";

    public void run() {
        System.out.println("Computer is running");
    }
}

public class Cpu extends Computer {
    public String name = "Cpu ";

    public Cpu() {
        System.out.println("Constructor of cpu");
    }

    public void run() {
        System.out.println("Constructor cpu is running");
        System.out.println(this);
    }

    public void getComputerName() {
        System.out.println(super.name + " Really?");
    }
}

public class main {

    public static void main(String[] args) {
        Cpu c = new Cpu();
        c.run2();
    }
}

打印:

Constructor of cpu
Machine is running
Machine
Constructor cpu is running
Cpu@1db9742

我的问题是,为什么当我们将 this 关键字与函数一起使用时,它会转到 this 引用的位置并激活函数,但是当我们将它与字段一起使用时,它就会转到与当前类(class)的领域?就像示例中的那样

最佳答案

您不能覆盖变量,只能覆盖方法。您正在 CPU 中创建一个新变量,其中包含该值,而不是覆盖父类(super class)中指定的值。

<小时/>

与问题无关,但是:

CPU 不应扩展 Computer,因为 CPU 不是 Computer。使用“is-a”技巧来确定是否应该扩展。 Computer 'has-a' CPU,因此应使用组合。

关于Java继承和this关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29315511/

相关文章:

java - 程序无法运行,Java、StringBuilder、Array

Java:继承、实例变量和 this

javascript - 访问函数内部调用事件的 JQuery 对象

java使用这个词是可选的还是不是?

java - "Throws"有什么作用,它有什么用?

java - 比较两个集合用于比较两个文本文件的添加、删除、修改

java - 领域模型金融交易应用

c# - Linq关键字提取——限制提取范围

java - 将 onPostExecute 值返回到 RecyclerAdapter 的 onBindViewHolder

java - "this"java 查询点