Constructors in Java Programming

Constructors in Java Programming

Previous Home Next

 

To understand the constructor, it is similarly important to understand how it differs from a method.

Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract, final, native, static, or synchronized.

Constructors have no return type, not even void. 
Constructors have the same name as their class; by convention, methods use names other than the class name.
Constructors start with an uppercase letter.
Constructor names are usually nouns because class names are usually nouns.
Constructors use this to refer to another constructor in the same class with a different parameter list.

Use of This in constructor

Constructors use this to refer to another constructor in the same class with a different parameter list.
 
 Dog(String input) //constructor with parameter
Dog() //constructor without parameter

In the code, there are two constructors. The first takes a String input to name the instance.
 The second, taking no parameters, calls the first constructor by the default name "John/Mary Doe".

 

public class Dog
{
String name;
Dog(String input) //constructor with parameter
{
name = input;
}
Dog() //constructor without parameter
{
this("John/Mary Doe");
}
public static void main(String args[])
{
Dog p1 = new Dog("digger");
Dog p2 = new Dog();
}
}


Previous Home Next