Declaring Constructor
Constructor Declaration
In Java, objects are constructed. Every time you make a new object, at least one
constructor is invoked. Every class has a constructor, although if you don't create
one explicitly, the compiler will build one for you. There are tons of rules concerning
constructors. For now, let's focus on the basic declaration rules. Here's a simple example:
class Boo {
protected Boo() { } // this is Boo's constructor
protected void Boo() { } // this is a badly named,
// but legal, it is a method!!!
}
The first thing to notice is that constructors look an awful lot like methods. A
key difference is that a constructor can't ever, ever, ever, have a return type.
Constructor declarations can however have all of the normal access modifiers, and
they can take arguments (including var-args), just like methods.
The other BIG RULE, to understand about constructors is that they must have the same name as
the class in which they are declared. Constructors can't be marked static (as they
are associated with object instantiation), they can't be marked final
or abstract (because they can't be overridden). Here are some legal and illegal
constructor declarations:
class Boo2 {
legal constructors
Boo2() { }
private Foo2(byte b) { }
Boo2(int x) { }
Boo2(int x, int... y) { }
illegal constructors
void Boo2() { } // it's a method, not a constructor
Boo() { } // not a method or a constructor
Boo2(short s); // looks like an abstract method
static Boo2(float f) { } // can't be static
final Boo2(long x) { } // can't be final
abstract Boo2(char c) { } // can't be abstract
Foo2(int... x, int t) { } // bad var-arg syntax
}
Go To
Home
Interface Declaration
Declaring Class Members
Variable Declaration


















0 comments:
Post a Comment
Post a Comment