Saturday, December 28, 2019

Classes and Objects(Creating new objects in java)

Classes and Objects


Creating objects in Java


This program is an example to create classes and objects in Java. We have the following hands-on to understand how can we create classes and objects in Java.

Problem statement:


Create a class Employee with fields emp_id, emp_name, basic_sal, HRA, and income_tax. Create 5 objects of class Employee also print the salary of each employee.

To calculate salary use formula,

salary=basic_sal + HRA - income_tax


Program


First, create a class with the name Employee.

public class Employee {
//Attributes
int emp_id;
String emp_name;
int basic_sal;
int HRA;
int income_tax;
//Attributes

public Employee(int emp_id, String emp_name, int basic_sal, int hRA, int income_tax) 
{
super();
this.emp_id = emp_id;
this.emp_name = emp_name;
this.basic_sal = basic_sal;
HRA = hRA;
this.income_tax = income_tax;
}
//method
public void displaySalary()
{
System.out.println(emp_name+" salary is "+(basic_sal+HRA-income_tax));
}
}


Create another class with any name(we have named it Demo) but it must have the main() method inside it

public class Demo {

public static void main(String[] args) {
//the main() method
//Create the objects
Employee emp1=new Employee(12, "Alex", 56500, 3650, 2525);
Employee emp2=new Employee(35, "John", 78450, 5550, 3525);
Employee emp3=new Employee(7, "Steve", 55570, 3645, 2525);
Employee emp4=new Employee(78, "Felix", 63400, 4500, 2525);
Employee emp5=new Employee(54, "Lewis", 537400, 3550, 2525);

//calculate salary of each employee
emp1.displaySalary();
emp2.displaySalary();
emp3.displaySalary();
emp4.displaySalary();
emp5.displaySalary();
}
} 

Results

The following results will be obtained

Alex salary is 57625 
John salary is 80475 
Steve salary is 56690 
Felix salary is 65375 
Lewis salary is 538425