There are many ways to create an object in java. They are:
- By new keyword
- By newInstance() method
- By clone() method
- By deserialization
- By factory method etc.
1.Anonymous object
Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For example:
new Calculation();//anonymous object
Calling method through a reference:
Calculation c=new Calculation();
c.fact(5);
Calling method through an anonymous object
new Calculation().fact(5)
Let's see the full example of an anonymous object in Java.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with anonymous object
}
}
output
2.Creating multiple objects by one type only
We can create multiple objects by one type only as we do in case of primitives.
Initialization of primitive variables:
Initialization of refernce variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
//Java Program to illustrate the use of Rectangle class which
//has length and width data members
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
output
As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
3.Object and Class Example: Initialization through a constructor
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
output
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0