How to call an overridden method?

A

Aaron Fude

Queston is in the comment. Thanks so much!

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

publicclass B extends A {
void f() {
System.out.println("B");
}
}


public static void main(String[] args) {
B b = new B();

// What's the syntax for calling A.f() on b?

}
 
A

Ajay

Queston is in the comment. Thanks so much!
 public class A {
    void f() {
      System.out.println("A");
    }
  }
  publicclass B extends A {
    void f() {
      System.out.println("B");
    }
  }
 public static void main(String[] args) {
    B b = new B();
    // What's the syntax for calling A.f() on b?

 From the main() method?  None.  It would defeat the purpose of an  
overridden virtual method for the client of the class to be able to pick  
and choose which version of the method to use.

If you want your class to expose that as part of its API, you could  
provide a separate method that calls "super.f()".  That would allow for  
the functionality without going behind class B's back.  However, IMHO an  
API that supports that is ill-advised.  It begs the question as to why the  
method is virtual in the first place.  You may want to consider making it  
"final" instead of adding a new method to call the base class version.

Pete

Aaron:

Perhaps this is a design issue: Usually, there are better ways to do
things than calling base class's overloaded method.

What are you trying to do?
 
D

David A. Redick

Java doesn't have the ability (AFAIK) to have non-virtual methods.
So...
A a = new B();
B b = new B();
a.f();
b.f();

Both print "B"

In C++ you have to explictly say these are "virtual" to get that
behavior.
In Java it is implied and that's that.
No casting can get around the fact that methods are virtual.

Possible work arounds (sorta).
1) Add the "final" to A's f() to prevent any subclass from overridding
it.

2) Add a new method to B called superF() or something that just calls
super.f().
In other words just give them different names.

There may be a way to do this using the reflection API but I haven't
seen it and I don't think its likely.

Class pSuperClass = b.getClass().getSuperclass();
A realA = pSuperClass.newInstance();
realA.f();

But thats insane and the exactly the same as just writing:
A realA = new A();
realA.f();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,187
Members
46,729
Latest member
ScarlettJe

Latest Threads

Top