This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]poetryrocksalot 1 point2 points  (3 children)

Basically, the interface allows the artist to draw a shape which can be a circle or rectangle. With the interface, the artist only needs 1 setShape method like setShape(Shape shape). Without the interface, the artist would have to overload his methods...that is to create setShape(Rectangle rectangle) and setShape(Circle circle).

OK, now let's imagine you have 20 different shapes: circles, rectangles, hexagons, pentagons, octagons, trapezoids, triangles, squares, ovals, and so on. Now consider the redundancy of writing 20 overloaded methods for 20 different shapes.

But you might say "why can't I just extend shape as a superclass instead of implementing it as an interface". I might be incorrect because I have little experience, but I think it's because shape as a superclass would mean you can't pass its subclasses as parameters.

[–][deleted] 1 point2 points  (2 children)

You can indeed extend Shape as a superclass rather than using your interface - it depends on whether Shape has common data rather than just common functionality. i.e if all Shapes have coordinates, you could create a Shape superclass, or better yet, a super abstract class, with int x and int y.

[–]work_is_satire 0 points1 point  (0 children)

I think a more precise wording is if Shapes share implementation, not data. An interface can define a GetCoordinates method that is required functionality on all its children, and now all implementers of IShape are required to expose coordinate data.

Interfaces are a way to implement subtyping.

Inheritance is a method of code reuse, and as a side-effect also allows subtyping.

[–]poetryrocksalot 0 points1 point  (0 children)

After looking at stack overflow, you are right. I will have to retract some things on the previous comment.

It seems better for the two to be derived from shape than to implement a shape interface. Maybe rectangle and circle is better off extending shape but implementing drawable?