In Java, inside an abstract class can I get the instance of the concrete class that extends it?
You can derive concrete classes from an abstract class. You can derive abstract classes from an abstract class. An abstract class can be useful as a common type for parameters in methods. In java, the constructors of a subclass are inherited from its superclass.
Your abstract class doesn't "exist" at runtime, only concrete implementations can be instantiated. Any method that is defined in the abstract superclass and is not overridden in the concrete class can reference "itself" through the this reference.
A concrete class is a subclass of an abstract class, which implements all its abstract method. Abstract methods cannot have body. Abstract class can have static fields and static method, like other classes. An abstract class cannot be declared as final.
The only way to access the non-static method of an abstract class is to extend it, implement the abstract methods in it (if any) and then using the subclass object you need to invoke the required methods.
Yes, you can do this by calling this.getClass()
. This will give you the Class
instance for the runtime type of this
.
If you just want the name of the class, you could use this.getClass().getName()
.
Lastly, there are also this.getClass().getSimpleName()
and this.getClass().getCanonicalName()
. I use the former all the time to print readable class names to log files and the like.
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