Is that possible to initialize object directly as we can do with String class in java:
such as:
String str="something...";
I want to do same for my custom class:
class MyData{ public String name; public int age; }
is that possible like
MyClass obj1={"name",24};
or
MyClass obj1="name",24;
to initialize object? or how it can be possible!
Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With