Constructors

Ex: Platypus p1 = new Platypus;
 * Constructors-** Constructors are used to initialize the instance variables of an object. Constructors are methods. They are usually declared as **public** to allow any code in a program to construct new objects of the class.

A constructor may take arguments (parameters) that help define a new object. A constructor that takes no arguments is called a "no-args" constructor.
 * All constructors have the same name as the class. Constructors do not have any return data type, not even //void//.**

A constructor is similar to a instant method, but it differs from a method in that it never has an explicit return type, it's not inherited, and usually has different rules for scope modifiers.


 * Naming a Constructor-** Same name as the class, first letter is capitalized -- usually a noun
 * Return Type-** No return type, not even void
 * Default Constructor**- If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler
 * Parameterized Constructor-** A constructor given specific parameters
 * "this"** **Constructor-** Refers to another constructor in the same class. If used, it must be the first line of the constructor

An example code of a default Constructor and Parameterized Constructor

code format="java5" public class Cube1 {

int length; int breadth; int height; public int getVolume {       return (length * breadth * height); }   Cube1 < Default Constructor {       length = 10; breadth = 10; height = 10; }   Cube1(int l, int b, int h) <- Parameterized Constructor {       length = l;        breadth = b;        height = h;    } public static void main(String[] args) {       Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1; cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume); System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume); } }

code Constructors can be recognized by the word "new". For example, FilledRect meermans = new FilledRect(....); creates a new filled rectangle. They create objects and/or initialize data. - Default constructors: no parameters, you give things default values