0

I am wondering if it's possible to explicitly access a super class method in Java outside of the derived class. The following C++ code illustrates this:

#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.

I know this is horrible design, and totally breaks encapsulation, but is this possible in Java?

Ian Finlayson
  • 291
  • 1
  • 2
  • 11
  • something like super.nameOfYourMethod()? – Nico Apr 11 '13 at 23:57
  • 1
    you cant it violates encapsulation take a look here http://stackoverflow.com/questions/6386343/how-to-call-a-super-method-ie-tostring-from-outside-a-derived-class – Connr Apr 12 '13 at 00:05

2 Answers2

1

No, there isn't a way to do that directly, however, you can write a function within b to call a's 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(); in other words, calling the superclass a from within b.

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.

0

You can't do this in java. When you do this in C++ you know what you're doing, so it's not a problem. Java actually allows access to private methods an fields through the reflections API.

Tareq
  • 689
  • 1
  • 10
  • 22