Constructor demo - Java

Create a class called Employee that includes three pieces of information as instance variables—a first name (type String), a last name (type String) and a monthly salary (double). Your class should have a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test application named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary. Then give each Employee a 10% raise and dis- play each Employee’s yearly salary again.

Employee Class 

 class employee
{
        String fname;
        String lname;
        double salary;
      
        public void display()
        {
            System.out.println("First Name :" + getfname());
            System.out.println("Last Name :" + getlname());
            System.out.println("Salary :" + getsalary());
        }
      
        employee()
        {
        }
        employee(String fn, String ln, double sal)
        {
            setfname(fn);
            setlname(ln);
            if(sal<0)
            {
                sal = 0.0;
            }
            setsalary(sal);
        }
        void setfname(String fn)
        {
            fname = fn;
        }
        void setlname(String ln)
        {
            lname = ln;
        }
        void setsalary(double sal)
        {
            salary = sal;
        }
        String getfname()
        {
            return fname;
        }
        String getlname()
        {
            return lname;
        }
        double getsalary()
        {
            return salary;
        }      
}



Test Program



import java.util.Scanner;

class firstapp
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        String fn, ln;
        double sal;
       
        System.out.print("\nEnter First Name :: ");
        fn = sc.next();
        System.out.print("\nEnter Last Name :: ");
        ln = sc.next();
        System.out.print("\nEnter Salary Name :: ");
        sal = sc.nextDouble();
       
        employee emp = new employee(fn, ln, sal);
        emp.display();       
    }
}


 
 

Post a Comment