Java: Does a Size interface exist? – Education Career Blog

Does some interface like below already exist in Java?

interface Size {
    int getWidth();
    int getHeight();
}

Edit: It must be an interface.

,

I’d recommend making your own rather than using java.awt.Dimension, particularly if what you want is an interface and not a class. If you do want a class like Dimension, I still wouldn’t use it, but instead make another class as an immutable value type… Dimension‘s mutability is a major weakness. Every method that returns a Dimension is forced to return a copy of it, and every method that accepts a Dimension is forced to make a copy of it too. Had it been immutable, copying wouldn’t have been required in either case.

,

If you’re ok using a class and importing an AWT class you can use java.awt.Dimension or java.awt.geom.Dimension2D as an abstract base class. There isn’t a specific interface that I know of though.

,

The Dimension class? http://download.oracle.com/javase/6/docs/api/java/awt/Dimension.html

It isn’t final, you can extend and overwrite it for your own use.

,

A somewhat correct answer being given, I’d say my reservations about it. If you are doing a desktop project with awt/Swing – you can java.awt.Dimension, although it is not an interface. If you however want it indeed to be an interface – create your own.

Another reason to define your own Size interface, as shown in the question is because with Dimension you are creating a dependency on the AWT package. I hope that in the future internal dependencies in the JDK will be minimized and you will be able to run your server-side code without the need to include awt dependencies at all.

So ultimately my answer is – create your own interface.

Leave a Comment