I have 2 classes. Let's call them class A and class B. Class A contains a method that executes some action. Class B overrides this method with its own version, but does make a super
call to that method in class A to perform an action. Right now, this is working fine. However, there are some actions in class A that should only be executed if the object is only an instance of class A. Put another way, some actions in the Class A method should not happen if the object is an instance of a child of Class A.
Currently, I'm using instanceof
to check for each child, but I need to specify each child class, so if a new child is added at a later date, this method needs to be updated. What I would like is a dynamic way of determining if the object is a child class.
Are there any good alternatives, or is instanceof
the way to go?
public class A{
public void someMethod(){
// Only perform these actions if it is not a child class. This is what
// I am looking for a better solution for
if(!(this instanceof B)){
// Some action...
}
// Actions to execute for every call
}
}
public class B extends A{
@Override
public void someMethod(){
super.someMethod();
// More actions
}
}
Just as an explanation of the design, I am using it to generate XML. In the program, I have a List<A>
to store the data. When it is time to output the XML, I loop through the list and call generateXML
(the someMethod
takes its places in my example).
When an object of class A is created, it needs to have its data within <A></A>
tags. When an object of class B is created, it needs to have its data within <B></B>
tags. But all the properties of A
must also be inside the <B></B>
tags, so as of right now it calls the same generateXML
method used when an object is only of of Class A
But as some others have pointed out, calling that same method isn't the way to go. Class B
should be calling a protected method in class A
that only generates the necessary information.
Create protected methods that do the class-specific things, and call them from someMethod(). Class A will provide its implementation, and if a subclass needs to effectively remove that code, then it can override the protected method with an empty implementation.
Don't fight polymorphism; use it to your advantage.
Example:
public class A {
protected void someOtherMethod() {
// Do stuff specific to A here.
}
public void someMethod() {
// Do some stuff
someOtherMethod();
// Do some more stuff
}
}
public class B extends A {
@Override
protected void someOtherMethod() {
// Empty implementation; B doesn't need to do this.
// Or do stuff specific to B...
}
}
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