A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

A Simple Case Study:

A Simple Java Case Study

A Simple Case Study in Java

We will be creating two classes for our case study. The classes are Employee and EmployeeTest.

Instructions: First, open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now save this source file with the name Employee.java.

The Employee class has four class variables name, age, designation and salary. The class has one explicitly defined constructor which takes a parameter.

Example:-






import java.io.*;
public class Employee
{ 
 String name; int age; 
 String designation; 
 double salary;
 
 /* This is the constructor of the class Employee.*/
 
 public Employee(String name)
 { 
  this.name = name; 
 }
 
 /*Assign the age of the Employee to the variable age.*/ 
 public void empAge(int empAge)
 { 
  age = empAge; 
 }
 
 /* Assign the designation to the variable designation.*/ 
 public void empDesignation(String empDesig)
 { 
  designation = empDesig;
 }
 
 /* Assign the salary to the variable salary.*/ 
 public void empSalary(double empSalary)
 { 
  salary = empSalary;
 }
 
 /* Print the Employee details */ 
 public void printEmployee()
 {
  System.out.println("Name:"+ name );
  System.out.println("Age:" + age );
  System.out.println("Designation:" + designation );
  System.out.println("Salary:" + salary);
 }
}


 

As mentioned previously in this tutorial processing starts from the main method. Therefore in-order for us to run this Employee class there should be main method and objects should be created. We will be creating a separate class for these tasks.

The given below is the EmployeeTest class which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

Save the following code in EmployeeTest.java file:-






import java.io.*;
public class EmployeeTest
{
 public static void main(String args[])
 {
  /* Create two objects using constructor */
  Employee empOne = new Employee("James Smith");
  Employee empTwo = new Employee("Mary Anne");

  /* Invoking methods for each object created */
  empOne.empAge(26);
  empOne.empDesignation("Senior Software Engineer");
  empOne.empSalary(1000);
  empOne.printEmployee();
  empTwo.empAge(21);
  empTwo.empDesignation("Software Engineer");
  empTwo.empSalary(500); empTwo.printEmployee();
 }
}


 

Now, lets compile both the classes and then run EmployeeTest to see the result as follows: C :> javac Employee.java
C :> vi EmployeeTest.java
C :> javac EmployeeTest.java
C :> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer Salary:1000.0
Name:Mary Anne Age:21
Designation:Software Engineer Salary:500.0

LEARN TUTORIALS

.

.