简体   繁体   English

使用Java从外部访问超类

[英]Access Super Class from Outside in Java

I am wondering if it's possible to explicitly access a super class method in Java outside of the derived class. 我想知道是否有可能在派生类之外显式访问Java中的超类方法。 The following C++ code illustrates this: 以下C ++代码说明了这一点:

#include <iostream>
using namespace std;

class A {
  public:
    virtual void f( ) {
      cout << "A\n";
    }
};

class B : public A {
  public:
    void f( ) {
      cout << "B\n";
    }
};

int main( ) {
  B b;
  b.A::f( );
  return 0;
}

This code outputs "A" because it calls the A version of f explicitly. 此代码输出“ A”,因为它显式调用f的A版本。

I know this is horrible design, and totally breaks encapsulation, but is this possible in Java? 我知道这是可怕的设计,并且完全破坏了封装,但是在Java中这可能吗?

No, there isn't a way to do that directly, however, you can write a function within b to call a's f(). 不,没有直接执行此操作的方法,但是,您可以在b内编写一个函数来调用a的f()。

class a {
    public void f() {
        System.out.println("hi");
    }
}

class b extends a {
    public void f() {
        System.out.println("hi2");
    }

    public void f2() {
        super.f();
    }
}

Notice that you cannot access a's f() from b , however, f2() calls super.f() ; 注意,您不能从b访问a的f() ,但是f2()调用super.f() in other words, calling the superclass a from within b. 换句话说,从b内部调用超类a。

super is the superclass invocation, and while it cannot be called from the outside, you can design the class in such a way as to be able to call it internally. super是超类的调用,虽然不能从外部调用它,但是您可以以可以在内部调用它的方式设计该类。

You can't do this in java. 您无法在Java中执行此操作。 When you do this in C++ you know what you're doing, so it's not a problem. 当您使用C ++进行此操作时,您就知道自己在做什么,所以这不是问题。 Java actually allows access to private methods an fields through the reflections API. Java实际上允许通过反射API访问私有方法和字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM