Java - the scope of keyword this when overriding methods

Viewed 147

I am a bit confused about the keyword this in Java, I thought this is referring to the current object. In the below example I have created a class A and a class B that extends A. In the main function when I call the printMyArray function it prints 1 2 3 instead of 4 5 6 7. Is there a way for me to call the printMyArray function and print the array that is initialized in B? So far I can achieve it by having an exact same method in class B as well but I feel it is not the best way to do it.

public class Main {

    public static void main(String[] args) {

        B b1 = new B();
        b1.printMyArray();
    }
}

class A {
    private int[] numbers = {1,2,3};

    public void printMyArray() {
        for(int i =0; i < this.numbers.length; i++){
            System.out.println(numbers[i]);
        }
    }
}

class B extends A {
    private int[] numbers = {4,5,6,7};
}
3 Answers
Related