tags:

views:

227

answers:

5

In java we can use instanceOf keyword to check the isA relationship. But is it possible to check hasA relationship too?

+1  A: 

If you write your own method to do it.

public class Human {

    private Human parent;

    ..
    public boolean hasParent() {
         return parent!=null;
    }

}
pjp
@PJP and @Scharrels, i guess this will work for me.
Rakesh Juyal
+2  A: 

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.

Stephen C
A: 

The plain association/aggregation constructs are not language elements, you write them in the program code. So you write the checker methods too.

+3  A: 

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.

Jon Skeet
actually it will be 'good to have' functionality. The point is, suppose you want to execute some method if the classing is having the object of Class1 then you can do this easily if there is some keyword 'having' just like 'instanceOf'. Though i am satisfied with the answer of PJP and Scharrels.
Rakesh Juyal
I can't say I agree that it would be "good to have" at the moment. You'd have to show me a concrete example where this is the most elegant design *and* where an extra language feature would make it better.
Jon Skeet
+1  A: 

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().

Scharrels