Sign in to follow this  
de_matt

Java API method(s) returning abstract type

Recommended Posts

Hi there, The Java class Rectangle2D has a method called createIntersection. Here's the description from the Java API:
Quote:
public abstract Rectangle2D createIntersection(Rectangle2D r) Returns a new Rectangle2D object representing the intersection of this Rectangle2D with the specified Rectangle2D. Parameters: r - the Rectangle2D to be intersected with this Rectangle2D Returns: the largest Rectangle2D contained in both the specified Rectangle2D and in this Rectangle2D. Since: 1.2
From Java API My question is how can the method return a new Rectangle2D object when Rectangle2D is an abstract class? There are other methods similar to this. Some of these could be returning a reference to the Rectangle2D part of a derived class object (like a cast I presume). But this method says it creates a new object of type Rectangle2D. Can anyone explain this to me? Thanks Matt

Share this post


Link to post
Share on other sites
Quote:
Original post by de_matt
My question is how can the method return a new Rectangle2D object when Rectangle2D is an abstract class?

1. This method doesn't actually return anything because it is abstract.
2. You can't really return objects in Java (and you can't pass objects, and you can't store objects in variables).
3. What kind of object is actually created is determined by the implementations of the abstract method in Rectangle, Rectangle2D.Double and Rectangle2D.Float.

Share this post


Link to post
Share on other sites
Since Rectangle2D is abstract, you can't create a Rectangle2D upon which to call the method anyway, so there is no problem. The purpose of the method in the abstract base is to specify the behaviour of the children. Thus, every concrete child class of Rectangle2D supports a method called createIntersection, which will accept an instance of any (the same, or any other) concrete child class of Rectangle2D, and will return the intersection as an instance of some unknown concrete child class of Rectangle2D. You can store the result of the function call in a Rectangle2D variable, and call the same interface methods, but you don't know exactly what kind of Rectangle2D you got back unless you hack around with trial casting or instanceof checks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this