MaxDevelop
MaxDevelop

Reputation: 637

Java Inheritance and this keyword

look at this code

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();
    }
}

Prints:

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

My question is why when we using this keyword with function, it goes to where this refers and active the function, but when we use it with field it just go with field of the current class? like in the example

Upvotes: 0

Views: 104

Answers (2)

Vince
Vince

Reputation: 15146

You cannot override variables, only methods. You are creating a new variable in CPU which contains the value, not overriding the value specified in the superclass.


Not related to the problem, but:

CPU shouldn't extend Computer, since a CPU is not a Computer. Use the 'is-a' trick to determine whether you should extend. A Computer 'has-a' CPU, so composition should be used.

Upvotes: 2

Ori Lentz
Ori Lentz

Reputation: 3688

When you are exeucting run2 method for Cpu, the parent method in Machine is called because it is not overriden in Cpu. In that scope, this.name refers to Machine's field.

When run2() in Machine calls this.run(), it calls it on the object which is being executed - Cpu. Cpu overrides run(), and so that method is called. Inside Cpu.run's scope, the field name is that of the Cpu class. "this" refers to the Cpu class as well.

Upvotes: 0

Related Questions