Constructor in java short note with example program
constructor
Initialize the instance variable and does not return any value, not even void.
Before understanding what is constructor , let's see how object is created
Syntax of object creation
Classname objectname=new constructor();
here new is java keyword used to create an object (instance)
constructor are called automatically when a new object is created
when an object is created in java using the keyword new following things happen:
Memory is allocated for new objects
Instance variables of the objects are initialized, either to their initial values or to default values(0 for number,null for objects)
A constructor is invoked
Constructor() is used to initialize the object
Rules to be followed creation of constructor
constructor name must be equal to class names
constructor does not have return type
It is entirely different from a method but working is similar to the method
There are two types of constructor in java
1 Default constructor
2 Parameterized constructor
Example program in default constructor
class Student
{
String name;//here string is data type
int age;//int is another data type
public static void main(String args[])
{
Student std=new Student();
System.out.println(std.name);
System.out.println(std.age);
}
}
Output from CMD
observe the program and its output
A constructor without any argument is called a default constructor
parameter constructor means we can passing some inputs in the
object creation itself ,this type of constructor is called parameterized constructor
more notes in java
constructor overloading in java example program
static keyword in java
Comments
Post a Comment