Richard
Richard

Reputation: 7

Setting a Class(object) to a variable

In Java, is it possible to assign a class or class object to a variable?

ThatClass obj= a; //a is any constant

Instead of ThatClass obj=new ThatClass(); //where the constructor is called and the integer (or any other value) in that constructor is then called/printed (see below).

ThatClass(){

    final int constant=a;
    System.out.println(constant);

}

I suspect not, but then again, Java continues to surprise me.

Upvotes: 1

Views: 253

Answers (3)

amant singh
amant singh

Reputation: 518

No, There is no way you can do this.Basically, You are asking for boxing conversion and java only supports following boxing conversions.

From type boolean to type Boolean

From type byte to type Byte

From type short to type Short

From type char to type Character

From type int to type Integer

From type long to type Long

From type float to type Float

From type double to type Double

From the null type to the null type

*String is a special case.

Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

Upvotes: 0

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

You obviously can assign class object to another class if the the class whose object you are assigning is a sub type. For example consider a class

class Bird
{
pulic Bird(String name)
{
System.out.println(name);
}
}

And now you create a sub class parrot like this

class Parrot extends Bird
{
public Parrot()
{
super("Parrot");
}
}

Now you create an object of Parrot.

Parrot p=new Parrot();

You can assign this to Bird

Bird b=p;

Even if you create a object of Bird like following

Bird b1=new Bird("A Bird");

You can assign this to another Bird variable like the following

Bird b2=b1;

If you want to access some fields of the class without creating objects of that class you have to decalre those fields as static.

class MyClass
{
final static int constant=a;
public static void show()
{
System.out.println(constant);
}
}

You can call the show() method like the following

MyClass.show();

Upvotes: 1

Ravindra HV
Ravindra HV

Reputation: 2608

Yes.

Class classType = String.class;
System.out.println(classType)

Should work.

Upvotes: 0

Related Questions