0

I have two Java classes, one of which inherits from other. They are somewhat like the following:

A.java:

public class A {
    public String invocations[] = {"foo"};

    public A() {
        // do stuff
    }
}

B.java:

public class B extends A {
    public String invocations = {"bar", "baz"};

    public B() {
        super();
    }
}

In this example, assuming I create an instance of B and get its invocations property, it returns {"foo"} instead of the expected {"bar", "baz"}. Why is this, and how can I get the {"bar", "baz"}?

BoxTechy
  • 339
  • 2
  • 6
  • 16
  • 3
    Your code, as written, will not even compile. So how do you know what the behavior will be? – EJK Apr 14 '18 at 02:44

1 Answers1

1

You have one variable hiding another one. You can refer to a variable in a super class by using a cast to the type explicitly. (I am assuming you fix the syntax errors)

public class Main {
    static class A {
        public String[] invocations = {"foo"};
    }

    static class B extends A {
        public String[] invocations = {"bar", "baz"};
    }

    public static void main(String... args) {
        B b = new B();
        System.out.println("((A)b).invocations=" + Arrays.toString(((A) b).invocations));
        System.out.println("b.invocations=" + Arrays.toString(b.invocations));
    }
}

prints

((A)b).invocations=[foo]
b.invocations=[bar, baz]
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130