creating multiple objects for a class.
-------------------------------------
We can create many objects for a class.
Program to create multiple objects for a car using parameter passing
-------
class Car
{
String name;
String color;
double price;
int cno;
public void input(String n,String c,double p,int no)
{
name=n;
color=c;
price=p;
cno=no;
}
//display method
public void display()
{
System.out.println(name);
System.out.println(color);
System.out.println(price);
System.out.println(cno);
}
}
class CarTest
{
public static void main(String args[])
{
Car car1=new Car();
Car car2=new Car();
Car car3=new Car();
car1.input("audi","red",60000.00,7777);
car2.input("bmw","pink",70000.00,6666);
car3.input("lamborghini","yellow",80000.00,5555);
car1.display();
car2.display();
car3.display();
}
}
In the above program we are creating 3 objects for Car class,
here 3 copies of objects are created in heap.
Every object will have its own copy of instance variables as shown in diagram.
For each method declaration one copy of method is created and this method is shared by all the objects of class as shown in diagram.
-------------------------------------
We can create many objects for a class.
Program to create multiple objects for a car using parameter passing
-------
class Car
{
String name;
String color;
double price;
int cno;
public void input(String n,String c,double p,int no)
{
name=n;
color=c;
price=p;
cno=no;
}
//display method
public void display()
{
System.out.println(name);
System.out.println(color);
System.out.println(price);
System.out.println(cno);
}
}
class CarTest
{
public static void main(String args[])
{
Car car1=new Car();
Car car2=new Car();
Car car3=new Car();
car1.input("audi","red",60000.00,7777);
car2.input("bmw","pink",70000.00,6666);
car3.input("lamborghini","yellow",80000.00,5555);
car1.display();
car2.display();
car3.display();
}
}
In the above program we are creating 3 objects for Car class,
here 3 copies of objects are created in heap.
Every object will have its own copy of instance variables as shown in diagram.
For each method declaration one copy of method is created and this method is shared by all the objects of class as shown in diagram.
No comments:
Post a Comment