Allows initialization of variables as soon as an object is created.
You make a constructor in very much the same way as a method, with the exception that the method name HAS to be the same as the class name.
When an object is created, the constructor is called before any methods.
When you don’t define a constructor, Java provides its own default constructor.
You define your own constructor to decide what values to give the instance variables.
Constructors don’t return values, not even void.
If you define a constructor, Java does not provide a default constructor.
The constructor name must be the same as the class.
// jamesprogram.java class jamesprogram { public static void main(String args[]){ cat catObject = new cat("Emma"); catObject.saying(); } }
When we create a new object above, we are passing the string “Emma” to the constructor of the cat class.
//cat.java public class cat { // private: only the methods inside this class can // read and change this variable private String friendsName; // THE CONSTRUCTOR public cat(String name){ friendsName=name; } public String getName(){ return friendsName; } public void saying(){ // printf uses %s as a string marker, and this // string is filled with the content of getName() System.out.printf("Your first friend was %s", getName()); } }
This outputs:
Your first friend was Emma
If we now change our program code
// jamesprogram.java class jamesprogram { public static void main(String args[]){ cat catObject = new cat("Emma"); cat catObject2 = new cat("Monkey"); catObject.saying(); catObject2.saying(); } } // This is a beauty of objects, they can't see // each other variables
We get the output:
Your first friend was EmmaYour first friend was Monkey
We created two separate objects