In java we can use instanceOf keyword to check the isA relationship. But is it possible to check hasA relationship too?
If you write your own method to do it.
public class Human {
private Human parent;
..
public boolean hasParent() {
return parent!=null;
}
}
I suppose that you could do this with Reflection, but I cannot see how this would be a useful thing to do in the context of Java. Java is designed to be a programming language, not an object modeling language.
EDIT - I'm assuming that you want to do this at a linguistic level ... rather than just coding a whole bunch of 'hasA' methods.
Do you mean you want to check if an object has a property of a particular type? There's no built-in way to do that - you'd have to use reflection.
An alternative is to define an interface which has the relevant property - then check whether the object implements that interface using instanceof
.
Why do you want to do this though? Is it just speculation, or do you have a specific problem in mind? If it's the latter, please elaborate: there may well be a better way of approaching the task.
The hasA relationship is often modeled as a private variable in a class:
Public class AClass {
private AnotherClass reference;
public AClass() {
reference = null;
}
public boolean hasAnotherClass(){
return reference != null;
}
// getters and setters are left out for readability
}
You can view and modify the reference using a getter and a setter. You can check for the relation using the method hasAnotherClass().