[Solved] Simple inheritance but confusing


The thing here is that your add method shadows the i attribute of the class with the i variable declared as parameter. Thus, when using i inside add method, you’re using the i parameter, not the i attribute.

To note the difference, change the add method to:

void add(int i) {
    System.out.println(5+i);
    System.out.println(5+this.i); //this will do the work for you
}

A good example of shadowing is used on class constructors:

public class SomeClass {
    int x;
    public SomeClass(int x) {
        //this.x refers to the x attribute
        //plain x refers to x parameter
        this.x = x;
    }
}

Follow up from comment:

got it , but what happens if i have the same member as i in JavaTest2 …and do the same this.i

This is called hiding and is well explained in Oracle’s Java tutorial: Hiding Fields

Example:

class JavaTest2 extends JavaTest {
    int i = 10;
    void add(int i) {
        System.out.println(5+i);
        System.out.println(5+this.i); //this will add 5 to i attribute in JavaTest2
        System.out.println(5+super.i); //this will add 5 to i attribute in JavaTest
    }
}

2

solved Simple inheritance but confusing