0

Method calls are always determined based on the runtime type of the object, however how can I call shadowed methods of base classes from an inherit instance?

class Base {
    String str = "base";
    String str() { return str; }
}

class Impl extends Base {
    String str = "impl";
    String str() { return str; }
}

class Test {
    public static void main(String[] args) {
        System.out.println(((Base) new Impl()).str);   // print 'base'
        System.out.println(((Base) new Impl()).str()); // print 'impl'
    }
}

For example above, how can I call the str() method of Base class from an Impl instance, preferably without using reflection?

MiP
  • 5,846
  • 3
  • 26
  • 41

1 Answers1

2

Using the Keyword super

Accessing Superclass Members

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). an example below.

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

calling printMethod since child class

Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

if you want to read more https://docs.oracle.com/javase/tutorial/java/IandI/super.html

Jorge L. Morla
  • 630
  • 5
  • 14
  • This answer is correct, but I'm looking for `shadowed methods of base classes`. So is your anwser the only solution to get the method deep inside multi-layer base classes? – MiP Dec 29 '17 at 14:01
  • I don't think it's possible but why would you want to? Why you shouldn't do this: https://stackoverflow.com/a/586397/4248317 – Cyril Dec 29 '17 at 14:14
  • @Cyril It's not that I want to, but I'm currently writing a minijava interpreter, so I need to get the behaviours as close to java compiler as possible. – MiP Dec 29 '17 at 15:26
  • method execution calls work since down to up, starting since child-class to super-class, searching the specified method jumping between classes till to find and call it, 'super' just have only one level toward to parent. your situation would break the abstraction rules. – Jorge L. Morla Dec 29 '17 at 17:20