initialize object directly in java
Asked Answered
N

11

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!

Nolie answered 17/8, 2012 at 12:13 Comment(5)
Like making constructors for the object?Campanulate
uhmm perhaps you want this docs.oracle.com/javase/tutorial/java/javaOO/annotations.html :)Angleaangler
i know that with constructors, but any alternative way is present or not?Nolie
no you can't, this is for assigning value as array to particular object. You can create overloading constructor as per your requirementKleptomania
C# has that facility, hope Java also had one. How to: Initialize Objects by Using an Object Initializer (C# Programming Guide) - msdn.microsoft.com/en-us/library/bb397680.aspxGyral
L
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!

Lingcod answered 17/8, 2012 at 12:15 Comment(5)
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?Myocardiograph
@Myocardiograph 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". jeezLingcod
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.)Myocardiograph
This initialization of a new class looked unfamiliar to me so I found that it is referred to as double brace initialization link. So it's basically an instance initialization block that is part of an anonymous inner class.Solvable
@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)Lingcod
T
14

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.

Topi answered 28/4, 2014 at 6:50 Comment(4)
Warning: by doing this you are actually creating an anonymous inner class, not just initializing an object. See this answer for an explanation of some potential pitfalls.Virility
@Virility why? I'm curiousLeavy
@Leavy 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.Virility
That was exacly what I was looking for. Thank you @Nick. This comment should be enriched whit that drawback. Knowing that you're not creating the object type you are instantiating is really important and changes everything in some cases.Topple
C
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");
Campanulate answered 17/8, 2012 at 12:16 Comment(0)
M
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);
Myocardiograph answered 17/8, 2012 at 12:21 Comment(1)
You're still going through a constructor (and thus have to write new ConstructorName which is what I think the OP wants to avoid).Myocardiograph
B
0

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

Bollix answered 17/8, 2012 at 12:15 Comment(2)
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.Nolie
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.Bollix
W
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);
Wove answered 17/8, 2012 at 12:16 Comment(2)
my question is for : MyClass obj1={"name",24};Nolie
then the answer is no. You can't!Wove
I
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
Iridis answered 16/8, 2017 at 7:38 Comment(1)
Object initializatian by construtor k = 45m = 65 object initializaion via method k = 34m = 56 object initialization via refrence a = 12 b =24Iridis
M
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.

Mayo answered 19/6, 2018 at 13:12 Comment(0)
S
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.

Sams answered 9/11, 2020 at 20:51 Comment(0)
G
0

I bet the OP was interested in object initialisation in a C-like fashion, similar to

Object [][] Tbl = {   
    { 8, "Aberdeen", "USA", "GMT-06:00", 4416, 72659, 45.45556, -98.41333 },   
    { 9, "Aberdeen", "UK", "GMT+00:00", 229, 3091, 57.205, -2.20528 },   
    { 10, "Aberporth", "UK", "GMT+00:00", 246, 3502, 52.13944, -4.57111 },    
    { 11, "Abidjan", "Côte d'Ivoire", "GMT+00:00", 3867, 65578, 5.25, -3.93333 },   
    { 12, "Abilene", "USA", "GMT-06:00", 4328, 72266, 32.41667, -99.68333 },     
    /* ... */  
    { 5128, "Zyryanka", "Russia", "GMT+11:00", 1426, 25400, 65.73333, 150.9 },   
};

where the above is meant to initialise a list of instances of a class with mixed-type fields:

class Station {
    int id = -1;   
    String name = null, country = null, timezone = null;   
    long sta_code = -1, wmo_code = -1;     
    double latitude = -90.1, longitude = 360.1;   
};

(The OP has asked for a single instance only) Yes, it's readily done using java reflection, by adding a varargs constructor that makes use of a reference to the class fields (any error checks are omitted below):

    private Field fields[] = this.getClass().getDeclaredFields();

    Station(Object... args) {
    // fileds.length decremented by one because we must skip
    // the last field (i.e., "Field fields[]" itself)  
        for(int i = 0; i < fields.length-1; i++)
            try {
                fields[i].set(this, args[i]);
            } catch(Exception e) {
                e.printStackTrace();
            }
    }

After that, just add following couple of lines

ArrayList<Station> stList = new ArrayList();
for(Object[] array : Tbl) stList.add(new Station(array)); 

and use the list as needed. E.g., one can add a method like

    void print() {
        String s = "";
        try {
            for(int i = 0; i < fields.length-1; i++)
               s += fields[i].getName() + "=" + fields[i].get(this) + " ";
        } catch(Exception e) { e.printStackTrace(); }
        System.out.println(s);
    }

to output the created list:

 for (Station st : stList) st.print();

and get

id=8 name=Aberdeen country=USA timezone=GMT-06:00 sta_code=4416 wmo_code=72659 latitude=45.45556 longitude=-98.41333  
id=9 name=Aberdeen country=UK timezone=GMT+00:00 sta_code=229 wmo_code=3091 latitude=57.205 longitude=-2.20528  
id=10 name=Aberporth country=UK timezone=GMT+00:00 sta_code=246 wmo_code=3502 latitude=52.13944 longitude=-4.57111  
id=11 name=Abidjan country=Côte d'Ivoire timezone=GMT+00:00 sta_code=3867 wmo_code=65578 latitude=5.25 longitude=-3.93333  
id=12 name=Abilene country=USA timezone=GMT-06:00 sta_code=4328 wmo_code=72266 latitude=32.41667 longitude=-99.68333   
...   
id=5128 name=Zyryanka country=Russia timezone=GMT+11:00 sta_code=1426 wmo_code=25400 latitude=65.73333 longitude=150.9

Of course, all this is for testing purposes only, and can hardly be recommended for use in the final code.

Gladiolus answered 14/12, 2023 at 8:32 Comment(0)
O
-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.

Onieonion answered 17/8, 2012 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.