Is there a Java equivalent or methodology for the typedef keyword in C++?

Viewed 132945

Coming from a C and C++ background, I found judicious use of typedef to be incredibly helpful. Do you know of a way to achieve similar functionality in Java, whether that be a Java mechanism, pattern, or some other effective way you have used?

12 Answers

Java has primitive types, objects and arrays and that's it. No typedefs.

If this is what you mean, you can simply extend the class you would like to typedef, e.g.:

public class MyMap extends HashMap<String, String> {}

There is no typedef in java as of 1.6, what you can do is make a wrapper class for what you want since you can't subclass final classes (Integer, Double, etc)

You could use an Enum, although that's semantically a bit different than a typedef in that it only allows a restricted set of values. Another possible solution is a named wrapper class, e.g.

public class Apple {
      public Apple(Integer i){this.i=i; }
}

but that seems way more clunky, especially given that it's not clear from the code that the class has no other function than as an alias.

Typedef allows items to be implicitly assigned to types they are not. Some people try to get around this with extensions; read here at IBM for an explanation of why this is a bad idea.

Edit: While strong type inference is a useful thing, I don't think (and hope we won't) see typedef rearing it's ugly head in managed languages (ever?).

Edit 2: In C#, you can use a using statement like this at the top of a source file. It's used so you don't have to do the second item shown. The only time you see the name change is when a scope introduces a name collision between two types. The renaming is limited to one file, outside of which every variable/parameter type which used it is known by its full name.

using Path = System.IO.Path;
using System.IO;

There is no need for typedef in Java. Everything is an Object except for the primitives. There are no pointers, only references. The scenarios where you normally would use typedefs are instances in which you create objects instead.

Related