如何制作数据类型并像Java中的普通变量类型一样填充它?

My condition is I have such a class like dataType and it's like this:

public class dataType{}

这甚至是可能的,如果是的话,如何并且如果没有,为什么要这样填写我的此类课程:

dataType x = "Hello World!";

要么

dataType x = 26;

The whole point is I don't want to fill a variable in dataType my case is about I want to add those object types directly and I am an Expert Java developer so I don't have a problem on knowing the normal way of doing this. I just want to be exactly like this. so if it is possible then how? and if not why?

使用Java 1.8。 谢谢。

评论
  • Veblen
    Veblen 回复

    如果要使用以下方法将元素分配给变量

    Type variable=<whatever>;
    

    ,左侧面板的类型需要与右侧的类型匹配。

    因此,您不能使用

    YourClass x = "Hello World!";
    

    since "Hello World!" is a String and not aninstance of your class.

    Old answer(because the class was named var):

    Since java 10, var is a keyword.

    You cannot name a class or variable or anything else with keywords.

    If you really want to name the class var, you need to use a java version lower than 10.

    However, this won't allow you to declare variables without explicitely defining the type.

    Anyway, class names should be PascalCase (start with a capital letter), so you should use Var instead.

    As the keyword is var and it is case sensitive, you can use Var as class name.