Joe
Joe

Reputation: 8042

Associating subclasses with ints and other Data in Java

Let's say I want to make a class to represent polygons, for example. And I wanted to make subclasses to represent specific shapes like triangles, quadrilaterals, or Pentagons.

This means that I will have classes that implement polygon that have a natural association with an integer. Is there a way I can represent this in my code? I guess what I really want is something similar to generics, except that they take numbers as arguments. For example, it would be nice if I could say something like Polygon<4> to refer to quadrilateral.

Upvotes: 0

Views: 64

Answers (2)

soulcheck
soulcheck

Reputation: 36767

You can create a factory with a method which returns object of the type you need depending on the number of vertices.

Something like PolygonFactory.createPolygon(numberOfVertices).

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160211

That would need to be a constructor argument, like "numberOfSides".

Upvotes: 0

Related Questions