I was wondering if there is a way to check with the if statement of which class an object is an instance of. I would need something like this:
if(object.getClass().equals("class Circle")) return object.radius;
Is this possible in Java?
I was wondering if there is a way to check with the if statement of which class an object is an instance of. I would need something like this:
if(object.getClass().equals("class Circle")) return object.radius;
Is this possible in Java?
The instanceof
operator should do the trick:
if (object instanceof Circle ) {
return ((Circle) object).radius;
}
Proximally, what you are looking for is instanceof
. However, the formulation betrays an inherent lack of understanding of Object-Oriented Programming in a strongly typed language:
//Start with no information about 'object'
if(object instanceof Circle) { //Figure out if it is a Circle
return object.radius; //If so, do something
}
In reality, in Java, you should already know what functions you're dealing with, at least for most situations:
public void getRadius(Object o) {
//Any old object may not even be related to a geometric thing; o could be a network socket!
}
public void getRadiusBetter(Shape s) {
//Shapes may or may not have a radius, but at least we are talking about shapes
}
public void getRadiusBest(Circular c) {
//By definition, c would have the state for the object's radius
}
For instance, we might define Circular as:
public interface Circular {
public double getRadius();
}
This guarantees any Circular object will be able to return a radius. In general, you want to formulate your code in this manner, taking advantage of strong typing, rather than assuming no information about the objects you're dealing with (as in Javascript or other weakly typed languages). Otherwise you could be stuck making many if-statements and convoluted logic to determine if you can even ask the appropriate questions of the objects you're dealing with. In Java, feel free to make reasonable checks, but always try to be as specific about your object as possible.
Remember, this:
f(x:TypeA) => y:TypeB
Can be guaranteed in a strongly-typed language, but not in a weakly typed one:
public TypeB f(TypeA x) { ... }
In JS you're dependent on the function doing what it says. In Java it will not compile if it fails.