Monday, November 4, 2013

Java default and overloaded Constructors

Implement a class Employee.An employee has a name and salary.
  • Write a default constructor.
  • Write a constructor with parameters(name and salary).
  • Write a member method printEmpDetails() which prints name and salary.
Implement another class EmployeeDemo which contains the main() and does the
following.

Create Employee object e with the following details
Name : Harry Smith
Salary : 10000

Print employee details using printEmpDetails().

Solution:

Employee Class ...
public class Employee {
    
    private String name;
    private float salary;
    
    //Creating Constructor
    //Default constructor
    Employee(){
        salary=0;
        name="noName";
    }
    
    //Constructor 2
    Employee(String name, float salary){
        this.name=name;
        this.salary=salary;
    }
    
    public void printEmpDetails(){
        System.out.println("Name: "+name);
        System.out.println("Salary: "+salary);
    }
}

EmployeeDemo Class ...
public class EmployeeDemo {
    
    public static void main(String args[]){
        
        //Creating Employee object
        Employee emp = new Employee("Harry Smith", 10000);
        
        //Calling method printEmpDetails()
        emp.printEmpDetails();
        
    }
}


No comments:

Post a Comment