- All objects that are created must be given initial values.
- Giving initial values to objects can be done using two approaches
- Using the dot operator to access the instance variables and then assign values to then individually
- The second method is with the help of method like getdata to initialize each object individually using statement like
Rect1.getdata
(15, 10);
- But it would be simpler to initialize an object when it is first created.
- Java allows objects to initialize themselves when they are created. This automatic initialization is performed throw the use of constructor.
- Constructor’s initializes an object immediately upon creation.
- It has the same name as the class and is syntactically similar to a method.
- Once the constructor is defined, the constructor is automatically called immediately after the object is created.
- Constructors have no return types not even void. This is because implicit return type of constructor is class type itself.
- By using constructor, creating instance is fully initialized and it is available to use immediately.
import java.io.*;
import java.util.*;
class identity
{
String name;
int age;
identity(String n,int a)
{
name=n;
age=a;
}
void printidentity()
{
System.out.println(" Name is" +name);
System.out.println("age is " +age);
}
public static void main(String[] args)
{
identity I;
I=new identity("shyam",30);
I.printidentity();
System.out.println("-----------");
I=new identity("reddy",3);
I.printidentity();
System.out.println("-----------");
}
}
the output of the above program is
In case of absence of constructor, the default constructor
automatically initializes all instance variables too.
Once you define your own constructor, the default
constructor is no longer used.
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.