Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Concrete Class name from Abstract Class

In Java, inside an abstract class can I get the instance of the concrete class that extends it?

like image 725
blong824 Avatar asked Aug 01 '11 16:08

blong824


People also ask

Can you derive concrete classes from an abstract class?

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.

Can an abstract superclass reference refer to its concrete subclass object?

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.

Is an abstract class a concrete class?

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.

How can we access concrete methods in abstract class?

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.


1 Answers

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.

like image 95
NPE Avatar answered Sep 28 '22 05:09

NPE