views:

546

answers:

6

I have an object for a subclass who is of it's superclass type. There is a overridden function in subclass which gets executed when called using the object. How to call the parent's function using the same object? Is there any way to achieve this?

package supercall;

public class Main {

    public static void main(String[] args) {
        SomeClass obj = new SubClass();
        obj.go();
    }

}

class SomeClass {
    SomeClass() {

    }
    public void go() {
        System.out.println("Someclass go");
    }
}

class SubClass extends SomeClass {
    SubClass() {

    }
    @Override
    public void go() {
        System.out.println("Subclass go");
    }
}

Consider the code above.

Here it prints

Subclass go

. Instead I have to print

Superclass go

.

+2  A: 

Instead of:

System.out.println("Subclass go");

Write

super.go();

(Or, you know, just don't implement that method ...).

Noon Silk
Yeah. But sometimes I would use subclass's method too. Isn't it possible to call the superclass's method in someother way? something like obj.super.go()??? Of course, this is a wrong construct. I meant something similar??
bdhar
Ohh man... i have just written that answer(not posted)... shit!!!
Webbisshh
@bdhar: Yeah, you can just call `super`. But you need to make that call from *in* the class. It can't be done externally.
Noon Silk
A: 

Is there any way to achieve this? No, there isn't.

At runtime the JVM will pick the methods to call based on the instance type (that's polymorphism for you), not based on the type it is declared with.

Your instance is a subclass instance, so the go() method in the subclass will be called.

dpb
A: 

One way would be to make the subclass call teh super classes implementation. But I'm assuming thats not what you want?

class SubClass extends SomeClass {
SubClass() {

}
@Override
public void go() {
    super.go
}

}

steve
+3  A: 

No, it's not possible, and if you think you need it, rethink your design. The whole point of overriding a method is to replace its functionality. If a different class knows that much about that class's internal workings, you're completely killing encapsulation.

Michael Borgwardt
A: 

@silky.. Could you please provide a example for what u mentioned in above thread-- "you need to make that call from in the class. It can't be done externally"

A: 

@Steve.. Calling superclass function using super keyword is indeed the correct way. What I wanted to know was if there is any other way to invoke the superclass go() method using "obj" as the reference??