Reputation: 1116
Given an interface:
public interface GoAlgorithm
{
public void go();
}
A class which implements the interface:
public class GoByFlyingFast implements GoAlgorithm
{
public void go()
{
System.out.println("Now I'm flying FAAAAST. Woo-hoo!");
}
}
An abstract class
public abstract class Vehicle
{
private GoAlgorithm goAlgorithm;
public Vehicle()
{
System.out.printf("A new vehicle has entered the race! \n");
}
public void setGoAlgorithm(GoAlgorithm algorithm)
{
this.goAlgorithm = algorithm;
}
public void go()
{
this.goAlgorithm.go();
}
}
A class extending the abstract class:
public class Tomcat extends Vehicle
{
public Tomcat()
{
setGoAlgorithm(new GoByFlyingFast());
}
}
(Code examples from Design Patterns for Dummies)
Is there a way, within the abstract class's implementation of the interface's method, to determine the subclass of the object invoking the method of the interface?
Can go() determine if a Tomcat object is invoking the go() method as defined by the Vehicle class?
Apologies if this question has already been posed. As evidenced by this question's title, I'm struggling to word my question concisely.
Thank you!
EDIT: Pure curiosity question
Upvotes: 1
Views: 838
Reputation: 1186
Theoretically yes. You can get the current stack trace with Thread.getStackTrace()
, analyze it and look at the dynamic class of your caller. However, this would be VERY bad design.
Alternatively you can have your subclasses implement a getName()
function, which returns their classname, so you could access that in your superclass.
In any case, it is good design if your (abstract) classes do not change their behavior based on which class is subclassing them. So there should not be a need for obtaining such information.
Upvotes: 1