We created a rather peculiar variable obj in our last tutorial(The infamous”hello world”).
Greetings obj = new Greetings();
Lets break it down.
Greetings obj- its is just a variable declaration.Its like declaring any other variable.
This variable is called an instance variable(we,ll talk about that in the post about variables..here just let it be.)
For example int x;
But in this case the variable is of type Greetings.FYI classes in java are like data types so it is valid to make arrays and variable of a class type.
new Greetings(); is creation of a new object. new is a java keyword,used to create memory space for objects.
Constructors are used to initialize all the class variables.So, you don’t output a null variable or operate a null variable(this is one of the reasonable reason ,they exist).
Greetings() is the constructor of the class Greetings.When an new keyword is found by the java compiler it immediately allocates space for it in the memory and calls the constructor to the object.
Constructor is a method that has the same name as the class.It does not return.
For eg-int Greetings() is not a valid constructor declaration.The correct one is Greetings(){};
Even if you don’t provide for a constructor in your code java will provide a default constructor for you, initializing all your instance variables to their default values i.e int variable to 0, Boolean to false and char to null. It is always a good programming practice to provide a no parameter constructor.
Now,constructor is just like any other method. That means they can be overridden.
for eg- a constructor can be defined as Greetings(int x ,int y);
Our class Greetings can now be defined as-
public class Greetings { String greet ; //class variable
Greetings(){}; //no parameter constructor
Greetings(String s) { /** this constructor accepts a string and assigns it to the class variable greet */
greet = s ;
void displayGreeting(){
Constructors can also call other constrictors. this keyword is used to do so. this(x,y) calls its fellow constructor that accepts two variables.
This pretty much concludes our discussion about constructors.This is almost everything you need to know about constructors…Watch out for the next tutorial..See you next time 😀