javainheritancecustom-type

Is there a way in Java to build custom types based on java.lang base Types (e.g. String)?


is there a way in Java to create a custom class based on a primitive Java base class to give the derived class a semantic?

Example: I want to create a LinkedHashMap<LastName, Age> ages where LastName is a custom type of String and Age a custom type derived from Integer. I just tried to create my own class

public class LastName extends String {
    //(no code in here, LastName has the same functionality as String)
}

but this is not possible. Is there another way to achieve what I want?


Solution

  • What you probably want is type-aliases. Java does not support this.

    The best way would be to create a wrapper class, something like this:

    class LastName{
        private String value;
    } 
    

    Another way is to name your variables correctly, eg don't do:

    String string = "Smith";
    

    But rather do:

    String lastName = "Smith";
    

    or just document your code with comments and javadoc.


    Sidenote: If you still want to use type aliases you may want to use the Kotlin programming language which can compile to java-code (and more).