user3107811
user3107811

Reputation: 55

How to create an object without invoking its constructor?

Is it possible to create an object reference without invoking its constructor? For example, I have a main class that initializes a bunch of things in the constructor. In doing so, I've also created some getter methods in order to access some of the variables in this main class.

The problem is that in my other class when I create a new instance of the object it runs the constructor again. I only want a reference to the class so I can use the getter methods in it.

Upvotes: 0

Views: 66

Answers (1)

Salih Erikci
Salih Erikci

Reputation: 5087

Then you should use static methods.

public class MyClass{
 private static int x;

 public static int getX(){
  return x;
 }
}

Now to reach x, you should use MyClass.getX();

Upvotes: 2

Related Questions