Accessing a superclass function using a subclass object

I have a subclass object extending its superclass. The subclass has an overridden method that can be called using the object. Is it possible to call a superclass function using a subclass object?

package supercall; public class Main { public static void main(String[] args) { SomeClass obj = new SubClass(); obj.go(); //is there anything like, obj.super.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 he is typing

Subclass go

. Instead, I have to print

Superclass go

.

+5
source share
5 answers

No, this is 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 another class knows about it, then you completely destroy encapsulation.

+15
source

Here it prints a subclass of go, Instead I have to type a superclass of go

Well, then do not override the go method @subclass method, it will call the implementation of the superclass.

If you want to run a super implementation and have another additional @subclass class, you call super.go (); and then run some other statements.

This is normal, since you are reusing already written code, you should not copy-paste the code from the superclass and put it in subtitles, like duplicating the code. But if your goal is to completely change the behavior, then do not call super

+3
source

Instead:

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

Record

 super.go(); 

(Or, you know, just do not implement this method ...).

+2
source

Is there any way to achieve this? No no.

At run time, the JVM will select the methods to invoke based on the type of instance (this polymorphism is for you), and not based on the type with which it was declared.

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

0
source

One way would be for the subclass to invoke the implementation of superclasses. But I guess this is not what you want?

 class SubClass extends SomeClass { SubClass() {} @Override public void go() { super.go } } 
0
source

All Articles