WHAT IS CONSTRUCTORS?
A constructors initializes an object immediately upon creation . It has the same name as the class in which it resides and is syntactically similar to a method .Once defined, the constructor is automatically called immediately after the object is created,before the new operator completes. Constructors look a Little strange because they have no return type,not even void.This is because the implicit return type of a class’ constructor is the class type itself. It is the constructors’s job to initialize the internal state of an object so that the code creating an instance will have a fully initialized ,usable object immediately.
In Java, some of the differences between other methods and constructors are:
- Constructors never have an explicit return type.
- Constructors cannot be directly invoked (the keyword “
new” must be used).
- Constructors cannot be synchronized, final, abstract, native, or static.
WHAT IS THIS KEY?
The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword.
for example :-
/* Here , Demo uses a constructor to initialize the variable */
public class demo
/*This is the constructor for Demo*/
public demo(int a, int b)
/*compute the return addition , subtraction ,multiplication, division*/
public int add()
public int sub()
public int mul()
public float div()
public static void main(String args)
/* declare , allocate ,and initialize Demo object*/
demo d= new demo(23,5 );
Output is give below:-