Some people think that Constructor are used to create object , they are totally wrong. In actual constructor are used to construct the object, you cannot make object without invoking a constructor in java.
You cannot make a new object without invoking not only constructor of object's actual class type but also the constructor of each of its superclasses
Constructor are the code that runs whenever you use the keyword new .
So every class must have constructor including Abstract classes.
Points to remember for constructors are
1. dont have return type
2. name must match the class name
So why we use them ?
Actually constructors are used to initialize the instance variable state as follows
class Demo{
int age;
Demo(int age)
{
this.age=age;
}
}
Do you know each constructor must call their super constructor.
in the previous code block compiler will automatically add super() after this.age=age; line.
If we dont write any constructor in our java class then compiler automatically create default constructor .
You cannot make a new object without invoking not only constructor of object's actual class type but also the constructor of each of its superclasses
Constructor are the code that runs whenever you use the keyword new .
So every class must have constructor including Abstract classes.
Points to remember for constructors are
1. dont have return type
2. name must match the class name
So why we use them ?
Actually constructors are used to initialize the instance variable state as follows
class Demo{
int age;
Demo(int age)
{
this.age=age;
}
}
Do you know each constructor must call their super constructor.
in the previous code block compiler will automatically add super() after this.age=age; line.
If we dont write any constructor in our java class then compiler automatically create default constructor .
No comments:
Post a Comment