initialize object directly in java

前端 未结 10 1038
逝去的感伤
逝去的感伤 2020-12-08 04:26

Is that possible to initialize object directly as we can do with String class in java:

such as:

String str=\"something...\";

I wan

10条回答
  •  臣服心动
    2020-12-08 05:16

    Normally, you would use a constructor, but you don't have to!

    Here's the constructor version:

    public class MyData {
        private String name;
        private int age;
    
        public MyData(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        // getter/setter methods for your fields
    }
    

    which is used like this:

    MyData myData = new MyData("foo", 10);
    


    However, if your fields are protected or public, as in your example, you can do it without defining a constructor. This is the closest way in java to what you want:

    // Adding special code for pedants showing the class without a constuctor
    public class MyData {
        public String name;
        public int age;
    }
    
    // this is an "anonymous class"
    MyData myData = new MyData() {
        {
            // this is an "initializer block", which executes on construction
            name = "foo";
            age = 10;
        }
    };
    

    Voila!

提交回复
热议问题