If I have a base class
Base thing = null;
of which there is a subclass
class Subclass extends Base
and I instigate it as
thing = new Subclass
how would I call a method that is specifically in Subclass, but not in Base?
ex.
Base
has only method()
Subclass
has method()
and specialMethod()
the method specialMethod()
is the one I want to call.
You can override these methods in SubB1 or SubB2 to get a different behavior but to get to a "new" method defined in SubB1 you must declare an object of type SubB1. Cast obj to be of the type SubB1. Then you can call your subclass methods.
Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.
In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).
To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword. super() can be used only inside the subclass constructor and must be the first statement.
If you know that thing
contains a Subclass
, you can do:
((Subclass) thing).specialMethod()
The others have already mentioned how to cast objects to get an answer to your question, but asking that question in the first place points to a possible design problem. Some possible reasons:
You have to cast to the subclass to invoke the method:
Base thing = new SubClass();
((SubClass) thing ).specialMethod();
But if you're in this situation is probably a good indication you class design can be improved. So, before adding a lot of checks and casting like this:
public void xyz ( Base thing ) {
if( thing instanceof Subclass ) {
((SubClass)thing).specialMethod();
}
}
Consider moving the specialMethod()
to the base class.
If this is not possible then just work with the subclass directly:
SubClass thing = ...
// no need to cast
thing.specialMethod();
But of course, this depends on what you're trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With