I have an interface Fruit which is implemented in Apple and Banana. In my main class, Fruit is called as following:
Fruit fruit = new Apple();
How can I retrieve a String of "Apple"? Using
fruit.getClass().getName()
OR
fruit.getClass().getSimpleName()
gives a java.lang.NullPointerException
I am trying to avoid making a function in Apple
and Banana
e.g. getClassName()
.
EDIT: Adding more details/methods, since my simplified question above doesn't seem to point to the problem. Adding more than the below would mean copying the whole code. Again, the below is a simplification.
public class Clustering {
private DistanceMeasure measure; //Manhattan or Euclidean
private ClusterMethod method; //SingleLinkage or CompleteLinkage
private Clusterer clusterer;
public static void main(String[] args) {
new Clustering().start();
}
Clustering() {
measure = new Manhattan();
method = new SingleLinkage(measure);
clusterer = new Clusterer(method);
}
void start() {
clusterer = setMethod();
clusterer.next(); //would use the ClusterMethod to do some calculations; clusterMethod which is saved inside Clusterer class when creating the new class i.e. new Clusterer(method). the nullException occurs here
}
Clusterer setMethod() {
measure = new Euclidean();
if (method.getClass().getSimpleName().equals("SingleLinkage")) {
method = new CompleteLinkage(measure);
}
else method = new SingleLinkage(measure);
return new Clusterer(method);
}
}
Does the above seem correct? The nullException occurs when using the clusterer.next() which works fine without using setMethod().