WaveRunner
WaveRunner

Reputation: 67

How can an object be initialized within its own class?

I was under the impression that a new object can be created if there is a existing class for it.

public final class Suit implements Comparable {
  private String name;
  private String symbol; 

  public final static Suit CLUBS = new Suit( "Clubs", "c" );

How does this work? What is the benefit of initializing within its own class as opposed to doing it in the main?

Thanks in advance.

Upvotes: 1

Views: 3250

Answers (4)

JRaymond
JRaymond

Reputation: 11782

a class is itself an object, that implements methods - such as newInstance() which gets you an object of type class. I know that wasn't the clearestDefinition but here's kind of how it works:

Whenever you create a new Object of type MyClass, the classloader first retrieves and creates an object that represents your class:

Class<?> MyClassObject

which performs a silent construction of all your 'static' variables. The program then asks MyClassObject for an instance of MyClass:

MyClass object = MyClassObject.newInstance()

static variables and methods belong to the MyClassObject, whereas instance variables belong to MyClass

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200296

This is a classic scenario for a typesafe enum (pre-Java 1.5) or for a singleton class. The benefit of initializing at the declaration site is that this is the only way for the field to be final, which is itself a very important characteristic.

Upvotes: 0

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

There are no any issues, because at the moment of instantiation whole information about the class structure is available and it can intantiated (no matter in a static or non-static field).

It's something like a recursive definition - which is totally legal:

   Node:
      Node parent;
      Node left;
      Node right;

Upvotes: 0

emory
emory

Reputation: 10891

Notice CLUBS is static. It is not part of any object but belongs to the class as a whole.

You could have initialized CLUBS in main, but then

  1. CLUBS would only be visible within the main method
  2. If you run java without a main method (e.g. web page there would be no CLUBS)

Upvotes: 1

Related Questions