Constructor in Java
Constructor:
1. It is used to initialize an object.
2. It is open type of special method.
3. It is used to provide values for the "instance" variables.
4. Constructor is invoked implicitly.
5. The java compiler provides a default constructor if you don't have any Constructor.
Rules:
1. Constructor should be having same name as class name.
2. It should not having any return type.
Syntax:
<Access Modifier><class name>()
Two types of constructor:
1. Default Constructor:
Constructor which has no parameters,known as Default Constructor.
2. Parameterized Constructor:
Constructor which has a parameters, known as Parameterized constructor.
Constructor will be called simultaneously whenever we are creating an object.
Keypoints in Java Constructor:
1. We are supposed to initialize an object with the available constructor present in the class.
2. If we are trying to initialize an object with the constructor which is not present in our class then we will be getting an compiler time error.
3. If we are not writing any constructor in our class, then java compiler automatically provide our program with a default compiler.
4. If we are providing either a parameterized constructor or a non parameterized constructor in our program then java compiler will not provide any default constructor for our program.
5. Default constructor and non-parameterized constructors both are same. Default constructor are given by compiler. Non-parameterized are gven by programmer.
6. For a constructor which is given by programmer ,we can use all the four access modifiers, that may be a constructor or a parameterized constructor.
7. For the default constructor provided by the compiler we can have only 2 access modifiers(public & default).
8. If want to restrict method calling in other classes then make your class constructor as private.
9. Just like void methods we can write 'return' statement inside a constructor without returning anything.
10.Constructor overloading is possible and overring is not possible.
Comments
Post a Comment