Is there a way that after you store something, such a Rectangle, to an object variable, say, Object x, that you can then look at object x, and determine it is indeed a rectangle, allowing you to use Graphic methods such as draw on said object?

Recommended Answers

All 4 Replies

Trying to answer quickly: I think you can write a class for Rectangle - what you define/mean for a rectangle---can write some methods to determine that it is a rectangle - check the length of the arms that each pair are equal. Check for angles [90 degrees] between arms.

for any object check, it is an instance of rectangle object... : 'instance of' is java built in.

You can also, execute the test method to determine it really is a rectangle...

Just tried to give some ideas...

I think there is something called: "instance of". I don't remember by heart how to use so might want to search it, but I do know that it works almost like this:

Rectangle r = new Rectangle();
if ( r instance of Rectangle ) {
}

But you'd better search it on the web to make sure.

Also you can try to do: r.getClass().toString() and then compare the String with the String Rectangle. Keep in mind that the above method also returns the package:

r.getClass().toString() returns packagename.Rectangle

This is wat you mean to do

Object obj =  new Rectangle();

if(obj instanceof Rectangle){
    ((Rectangle)obj).draw();
}

or

if(obj instanceof Rectangle){
    Rectangle r = (Rectangle)obj;
    r.draw();
}

The instanceof and casting seems to be what I was looking for, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.