44

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!

satvinder singh
  • 1,152
  • 1
  • 12
  • 22

10 Answers10

60

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!

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Doesn't work. You don't have any `MyData()` constructor if you've defined a `MyData(String name, int age)` constructor. **edit:** uhm.. I may have misunderstood here. You're suggesting to remove the constructor completely? – aioobe Aug 17 '12 at 12:26
  • 3
    @aioobe you've got to be kidding... I assumed that people would actually read "without a constructor" as meaning "without a constructor".. ie "define your class without a constructor". jeez – Bohemian Aug 17 '12 at 12:27
  • I read it as "you can construct a `MyData` object without using it's constructor" by using an anonymous subclass. Given your first snippet it didn't seem to work to me. (Besides, you're *still* using a constructor. I stand by my point: There's no way around that.) – aioobe Aug 17 '12 at 12:29
  • 1
    This initialization of a new class looked unfamiliar to me so I found that it is referred to as double brace initialization [link](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization). So it's basically an instance initialization block that is part of an anonymous inner class. – GregM Oct 25 '13 at 18:08
  • @user875298 your description is accurate, but "double brace initialization" is a poor moniker: is so happens that usually java's syntax results in two adjacent braces, but it is possible to do it without this (if you declare an instance variable or method for example) – Bohemian Oct 25 '13 at 20:51
13

If you have a class Person:

public class Person {

    private String lastName;
    private String firstName;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

You can actually create a new Person object and initialize its firstName and lastName with the following:

 Person person = new Person(){{
     setFirstName("My FirstName");
     setLastName("MyLastName");
 }}

This is used quite often when defining Spring Configuration using Java code instead of XML configuration.

Fengzmg
  • 710
  • 8
  • 9
  • 5
    Warning: by doing this you are actually creating an anonymous inner class, not just initializing an object. [See this answer](http://stackoverflow.com/a/27521360/2600833) for an explanation of some potential pitfalls. – Nick Nov 02 '15 at 20:13
  • @Nick why? I'm curious – ArCiGo Aug 18 '22 at 22:34
  • @ArCiGo This solution is making use of the anonymous class language feature: `new Person() { /* Person class can be extended here. The curly braces after parenthesis define an anonymous class. */ };`. In this case, only an initializer block is defined in the anonymous class. The initializer block is kind of like a constructor and allows us to invoke methods. Read up on anonymous classes and initializer blocks to understand this solution in more detail. – Nick Aug 19 '22 at 14:52
4

You have to make a constructor method for the object, which takes in parameters of the fields you want values for.

Example:

public myClass( int age, String name)
{
   this.age = age;
   this.name = name;
}

Then in the class you want this:

myClass class = new myClass(24, "name");
CBredlow
  • 2,790
  • 2
  • 28
  • 47
3

I know that with constructors, but any alternative way is present or not?

No, there are no alternatives to constructors.

That's basically one of the fundamental guarantees of the language. An object can't be constructed by any other means than through its constructors and there's no alternative syntax then the usual new ConstructorName(...).

The closest idea I can come up with would be to have a static factory method called say, mc:

class MyClass {
    ...
    public static mc(String name, int age) {
        return new MyClass(name, age);
    }
}

and then do

import static some.pkg.MyClass.mc;

...

MyClass obj1 = mc("name",24);
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • You're still going through a constructor (and thus have to write `new ConstructorName` which is what I think the OP wants to avoid). – aioobe Aug 17 '12 at 12:27
0

It is possible with the keyword new and using constructors, but not like the String, that is a very special kind of object.

Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
  • can you tell me the working of String class, how do it do that!, so i get some idea to implement to solve my problem. – satvinder singh Aug 17 '12 at 12:25
  • To be honest I am not sure about the internal implementation, however it is different because whenever you create a String literal using myString = "aString" as opposed to myString = new String("aString"), a new String is only allocated if and only if it is not already in the Java String pool. This Java string pool, contains all string literals that have been created so far, so it just references them from the pool instead of creating a new String object every time. – Oscar Gomez Aug 17 '12 at 12:29
0
class MyData{

    public MyData(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String name;
    public int age;
    }

Then you can instantiate your class this way:

MyData myData = new MyData("name", 24);
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0
    package com.company;

public class InitializationOfObject {
    int a ;
    int b ;

    InitializationOfObject(){
    }

    InitializationOfObject( int r , int n){
        this.a = r;
        this.b = n;
        System.out.println("Object initialization by constructor  ");
    }

    void methodInitialization(int k, int m){
        System.out.println("object initialization via method");
        this.a = k;
        this.b = m;
    }

    void display(){
        System.out.println("k = " +a+ "m = "+b);
    }

    public static void main(String... arg){
        InitializationOfObject io = new InitializationOfObject();
        InitializationOfObject io2 = new InitializationOfObject(45,65);
        io.a = io2.a;
        io.b = io2.b;
        io.display();

        io.methodInitialization(34,56);
        io.display();

        io.a = 12;
        io.b = 24;
        System.out.println("object initialization via refrence");
        System.out.println("a = "+io.a+" "+ " b ="+io.b);
    }

}

//Object initializatian by construtor

k = 45m = 65

object initializaion via method

k = 34m = 56

object initialization via reference

a = 12  b =24
Sergei Bubenshchikov
  • 5,275
  • 3
  • 33
  • 60
charu
  • 9
  • 2
  • Object initializatian by construtor k = 45m = 65 object initializaion via method k = 34m = 56 object initialization via refrence a = 12 b =24 – charu Aug 16 '17 at 07:39
0

There are two types of Constructors in java.

  1. Default constructor
  2. Parameterized constructor

You should create a parameterized constructor to create your object.

Yuresh Karunanayake
  • 519
  • 1
  • 4
  • 10
0

The following does what you want, but not in the way that you would expect.

So in a class calling MyData, you would use

Public MyData x = new MyData();
@PostConstruct public void init() {
     x.setName("Fering");
     x.setAge(18);
}

So once the object is construsted, these commands are run, which allows you to populate the object before anything else runs.

So with this you do not have to use anonymous subclasses, or create new constructors, you can just take the class and then use its functions, before anything else would.

Fering
  • 322
  • 2
  • 18
-1

There is no alternative to constructors (along with new operator) in java during the object initialization. You have mentioned as

String str = "something"

you can initialize string that way, because String is a literal in java. Only literals can initialized that way. A a composite object can not initialized, but only can be instantiated with the new operator with the constructors.

sakthisundar
  • 3,278
  • 3
  • 16
  • 29