-
Book Overview & Buying
-
Table Of Contents
OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
By :
As you learned in Chapter 1, a constructor is a special method that matches the name of the class and has no return type. Here's an example:
public class Bunny {
public Bunny() {
System.out.println("constructor");
}
}
The name of the constructor, Bunny, matches the name of the class, Bunny, and there is no return type, not even void. That makes this a constructor. Can you tell why these two are not valid constructors for the Bunny class?
public bunny() { } // DOES NOT COMPILE
public void Bunny() { }
The first one doesn't match the classname because Java is case sensitive. Since it doesn't match, Java knows it can't be a constructor and is supposed to be a regular method. However, it is missing the return type and doesn't compile. The second method is a perfectly good method, but is not a constructor because it has a return type.
Constructors are used when creating a new object. This process is called instantiation because...
Change the font size
Change margin width
Change background colour