Java: Calling function in “this” class rather than

2020-03-26 05:43发布

Is it possible in Java to invoke an overridable method in such a way that it always executes the "locally defined" version rather than an overridden version from a subclass? I.e. is there an analog to super that refers to this class, rather than the super class?

Let me give a code example to hopefully make it clear what I'm trying to do:

class A {
    void foo() {
        System.out.println("Foo from A");
    }

    void bar() {
        foo();  // <-- This is the important line!
    }
}

class B extends A {
    @Override
    void foo() {
        System.out.println("Foo from B");
    }
}

If I do new B().bar(), it will call the bar() method defined in A, which calls foo() as overridden in B to print "Foo from B".

Is there a way that I can force the bar() method to call the foo() method as defined in A rather than B? Just like I can use super.foo() in B to call the foo() method as defined in A? Unfortunately using this.foo() still calls the version of the subclass. Even something like ((A) this).foo() or A.this.foo() doesn't work.

Clearly, I could simply define a private or final version of foo() in A and call that instead. But I am hoping for a solution, where all I do is change the "important line" in the code sample above to a different way of invoking foo() to have it print "Foo from A", preferably without some trick like reflection.

8条回答
淡お忘
2楼-- · 2020-03-26 06:16

As others have stated there is no direct way to do it but you might consider a variant of this construct:

  void bar() {
    ClassA self = new ClassA();
    self.foo();  // <-- This is the important line!
  }
查看更多
狗以群分
3楼-- · 2020-03-26 06:18

There is this Rule of Thumb:

In Inheritance the most specific version of the method for that class is called.

- So it will be always the foo() method of Class B that will be called, if its called on an instance of B.

- Still if you want the foo() method of Class A to be called using your above mentioned code then you will need the super keyword.

Eg:

class B extends A {
    @Override
    void foo() {

       super.foo();
    }
}
查看更多
登录 后发表回答