Create an employee class(id,name,deptname,salary). Define a default and parameterized
constructor. Use ‘this’ keyword to initialize instance variables.Keep a count of objects created.
Create objects using parameterized constructor and display the object count after each object is
created.(Use static member and method). Also display the contents of each object.
import java.io.*;
import java.util.*;
class emp
{
int id;
String name;
String dname;
float salary;
static int cnt=0;
emp()
{
id=100;
name="Shreya";
dname="Computer Science";
salary=35000;
cnt++;
}
emp(int id,String name,String dname,float salary)
{
this.id=id;
this.name=name;
this.dname=dname;
this.salary=salary;
cnt++;
}
public void display()
{
System.out.print(" " +id);
System.out.print("\t" +name);
System.out.print("\t" +dname);
System.out.print("\t" +salary);
System.out.println();
}
}
class cdemo2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
emp e=new emp();
System.out.println("******* Default Employee Information************");
System.out.println("emp id \t ename \t dname \t salary");
e.display();
int n;
System.out.println("How many employee record you want");
n=sc.nextInt();
emp[] e1=new emp[n]; // object is created for parameterized constuctor
for(int i=0;i<n;i++)
{
System.out.println("Enter the emp id");
e.id=sc.nextInt();
System.out.println("Enter the emp name");
e.name=sc.next();
System.out.println("Enter the emp dname");
e.dname=sc.next();
System.out.println("Enter the emp salary");
e.salary=sc.nextFloat();
e1[i]=new emp(e.id,e.name,e.dname,e.salary);
}
System.out.println("********* Employee Information*********");
System.out.println("emp id \t ename \t dname \t salary");
for(int i=0;i<n;i++)
{
e1[i] .display();
}
System.out.println("Number of times object created is"+e.cnt);
}
}
0 Comments