If I have a parent class, for example Operacion
, and I have two child classes, for example Suma
and Resta
, how can I get the name in a format String
so that it returns "Sum" or "Subtraction" of the child classes from the parent class Operacion
?
Or simply with "super.toString()" you can inherit the toString methods from the parent class, which you can modify in your own way within the child class. It is always clear that you have extended and implemented the classes with which you want to inherit . I can't tell you more because I don't know if it's exactly what you're asking for. greetings mate
Since I'm here, in case you don't know very well how the "super" works, I've done it for you to understand and make things easier for you (it's a silly example)
Greetings and I hope I have helped you even if you already know the answer!
If the class name should always be returned without further ado, then you can use reflection. Create a method in the parent class like so
This avoids the need to override child classes. Here an example:
In case you use Java 8, you can enhance this functionality in a better way via interfaces as follows:
This allows other classes to have this same functionality without inheriting from the class
Operacion
.You can override the toString() method
Use:
Output:
Or you can create a method in the operation class and override it in its children.
Child class:
Use:
Output:
The secret is the @Override annotation
I think that what you need is to apply the concept of Polymorphism in Java. This is basically the definition of a method in a general way, that later a certain class will be in charge of giving functionality in a concrete way.
In java we can apply this concept by using interfaces or abstract class .
When should I use interfaces or abstract classes? Well, in my opinion, if you want to have certain methods implemented in a common way for a class hierarchy, you should use an abstract class . If you don't need those methods common to the hierarchy, it would be better to do it with interfaces . to code, first with an abstract class:
For all classes that extend the hierarchy, an implemented method is already offered, and another method is left to be implemented by each class:
The Concatenation class is not an arithmetic operation, so it also overrides the common method:
Here I give you a test to verify that I am not lying to you:
And if we had used an interface, what would the code be like... we create the interface we need:
And the base class for the hierarchy would be like this:
Coincidentally ;), the test works perfectly after this refactoring of the code without any change... object orientation is something very powerful and wonderful.