Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize object directly in java

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!

like image 249
satvinder singh Avatar asked Aug 17 '12 12:08

satvinder singh


People also ask

How do you initialize an object in Java?

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.

How do you initialize an 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 ( {} ).

How do you initialize an object in class?

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.

When can objects be initialized Java?

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.


1 Answers

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!

like image 151
Bohemian Avatar answered Sep 24 '22 23:09

Bohemian