1

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.

4
  • 1
    I don't understand very well what you're trying to do Commented Jan 12, 2017 at 19:14
  • What is it you really want to achieve? Your example is not that clear to me neither sorry. Commented Jan 12, 2017 at 19:17
  • I suppose that he wants to write the first line, but to get the behavior from the last section. But only @Richard can clarify this question. Commented Jan 12, 2017 at 19:20
  • Again, to clarify, I want the first line of code. Can you assign a class and its object to a variable or constant instead of resorting to "new" to call the constructor? Commented Jan 13, 2017 at 5:22

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Md. I understand this and this is not what I was wondering. I was wondering if a class and object could be set to a variable or a primitive type constant?
0

Yes.

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

Should work.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.