- Constructors will be executed when the object is created.
- Constructors should have same name of class name.
- Executed once per object.
- Basically used to assign instance variables
- We can overload constructors.
- We can call super class constructor form sub class constructor.
- package instanceofjava;
- class A{
- A(){
- }
- }
- }
- while creating object constructor will be executed so we can assign instance variables to some default values.
- package instanceofjava;
- class A{
- int a,b
- A(int x, int y){
- a=x;
- b=y;
- }
- public static void main(String[] args){
- A a=new A(10,20);
- }
- }
Types of constructors:
- There are two types of constructors
- Default constructors
- Parameterized constructor.
Default constructor:
- Default constructor will not have any arguments.
- If we not defined any constructor in our class. JVM automatically defines a default constructor to our class.
- package instanceofjava;
- class Sample{
- int a,b
- Sample(){
- a=37;
- b=46;
- }
- public static void main(String[] args){
- Sample obj=new Sample();
- System.out.println(obj.a);
- System.out.println(obj.b);
- }
- }
Output:
- 37
- 46
Parameterized constructor
- package instanceofjava;
- class Sample{
- int a,b
- Sample(int x, int y){
- a=x;
- b=y;
- }
- public static void main(String[] args){
- Sample obj=new Sample(37,46);
- System.out.println(obj.a);
- System.out.println(obj.b);
- }
- }
Output:
- 37
- 46
Constructor overloading:
- package instanceofjava;
- class Sample{
- int a,b
- Sample(){
- this(1,2);
- System.out.println("Default constructor");
- }
- Sample(int x , int y){
- this(1,2,3);
- a=x;
- b=y;
- System.out.println("Two argument constructor");
- }
- Sample(int a , int b,int c){
- System.out.println("Three argument constructor")
- }
- public static void main(String[] args){
- Sample obj=new Sample();
- System.out.println(obj.a);
- System.out.println(obj.b);
- }
- }
Output:
- Three argument constructor
- Two argument constructor
- Default argument constructor
- 1
- 2
No comments