Reputation: 67
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
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
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
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
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
Upvotes: 1