How do I implement these super class methods? - java

What I'm supposed to do:
write a java program to show the inheritance concept with an Employee being the super class and the Manager being the sub-class. Follow the following class structure: - Employee class
Variables:
Employee Number
Employee Name
Employee Salary
Constructor – Use this to initialize all the variables above Functions
Display() – This displays all the 3 variable values.
setSalary() – This sets the salary variable.
getSalary() – This gets the salary variable.
Heres what I have so far
public class Employee {
private int employeeNumber;
private String employeeName;
private double employeeSalary;
public Employee(int employeeNumber, String employeeName, double employeeSalary) {
this.employeeNumber = employeeNumber;
this.employeeName = employeeName;
this.employeeSalary = employeeSalary;
}
}
My question is how do I implement those three methods?
Are they just standard getters and setters?
I'm not familiar with the display function, if anyone can help with that
thanks!

You are really close. You need to create the manager Class and extend the Employee Class. But first let's add the described method for setting the salary and displaying all the fields!
Employee Class: The display() method concatenates the fields together separating them by line.
public class Employee {
private int employeeNumber;
private String employeeName;
private double employeeSalary;
public Employee(int employeeNumber, String employeeName, double employeeSalary){
this.employeeNumber=employeeNumber;
this.employeeName=employeeName;
this.employeeSalary=employeeSalary;
}
public void display(){
System.out.println("Employee Number: "+ employeeNumber +"\n"
+ "Employee Name: " + employeeName + "\n"
+ "Employee Salary: " + employeeSalary);
}
public double getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(double employeeSalary) {
this.employeeSalary = employeeSalary;
}
}
Manager Class: From general knowledge I would assume that a Manager could have multiple employees also.
So in this class you'd have specific methods for the Manager, such as adding a new Employee, or displaying or the Employees who work for a given Manager.
public class Manager extends Employee {
List<Employee> subordinates;
public Manager(int employeeNumber, String employeeName, double employeeSalary) {
super(employeeNumber, employeeName, employeeSalary);
subordinates = new ArrayList<>();
}
public void displayEmployees(){
for(Employee employee: subordinates){
employee.display();
// just print an empty line - so its prettier
System.out.println();
}
}
public void addNewEmployee(Employee employee){
subordinates.add(employee);
}
public List<Employee> getSubordinates() {
return subordinates;
}
public void setSubordinates(List<Employee> subordinates) {
this.subordinates = subordinates;
}
}
Testing: note that a Manager inherits all the methods of the Employee class, which is why within the Manager class there was no need to override the methods, but of course that can be done to add new functionality.
public class Main {
public static void main(String[] args) {
Manager manager = new Manager(11111, "Elon Musk", 42344);
manager.display();
// lets make some employees who work for the above manager
Employee employeeOne = new Employee(324, "Bob Den", 3522);
Employee employeeTwo = new Employee(44, "Tim Pipe", 4234 );
Employee employeeThree = new Employee(42, "Asif Blar", 4321);
// lets add the new employees to the managers list of employees ( this can further be refactored )
manager.addNewEmployee(employeeOne);
manager.addNewEmployee(employeeTwo);
manager.addNewEmployee(employeeThree);
// lets display all the employees who work for the manager
manager.displayEmployees();
// lets give the manager a 10 % raise
double employeeSalary = manager.getEmployeeSalary();
manager.setEmployeeSalary(employeeSalary +(employeeSalary /10));
// lets print out the managers hefty new salary
manager.display();
}
}

Related

Can anyone help me with "tostring" method in java?

Im doing an OOP assignment.. It has four classes Person, student and employee both extends person and instructor that extends employee. .
I have done Almost everything i could but i cant print out values using tostring method and Cant fill the array.I have used getter setter and all the constructor and methods are there still cant get any output. heres the person class and all the remain three classes have been made. plus the main file
abstract class Person
{
protected int Id;//"protected"Only child can use this
protected String Name;
public Person() {}
public Person(int id,String name)
{
this.Id=id;
this.Name=name;
}
public int getId()
{
return this.Id;
}
public void setId(int id)
{
this.Id=id;
}
public String getName()
{
return Name;
}
public void setName(String name)
{
this.Name=name;
}
public String toString()
{
return Id + Name + " is a student ";
}
public static int getMaxID()
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
public class Employee extends Person
{
protected double Salary;
protected String employeeName;
public Employee() {}
public Employee(double salary)
{
this.Salary=salary;
}
public Employee(String employeename)
{
this.employeeName=employeename;
}
public String getemployeeName()
{
return employeeName;
}
public void setemployeeName(String employeename)
{
this.employeeName=employeename;
}
public double getSalary()
{
return this.Salary;
}
public void setSalary(double salary)
{
this.Salary=salary;
}
public String toString()
{
return employeeName + " is an instructor earning a salary of " + Salary;
}
}
////////////////////////////////////////////////////////////////////////////////
public class Student extends Person
{
protected int teacherID;
protected String teacherName;
protected String studentName;
public Student() {}
public Student(int teacherid,String teachername)
{
this.teacherID=teacherid;
this.teacherName=teachername;
}
public Student(String studentname)
{
this.studentName=studentname;
}
public Student(String teachername, String studentname, Person[] person_array)
{
this.teacherName=teachername;
this.studentName=studentname;
}
public int getteacherID()
{
return this.teacherID;
}
public void setteacherID(int teacherid)
{
this.teacherID=teacherid;
}
public String getteacherName()
{
return teacherName;
}
public void setteacherName(String teachername)
{
this.teacherName=teachername;
}
public String toString()
{
return studentName + " is a student ";
}
}
////////////////////////////////////////////////////////////////////////////////
public class Instructor extends Employee
{
int[] studentID=new int[10];
protected String instructorName;
public Instructor(String instructorname)
{
this.instructorName=instructorname;
}
public Instructor(String instructorname, double salary)
{
this.instructorName=instructorname;
this.Salary=salary;
}
public double getSalary()
{
return Salary;
}
public void setSalary(int salary)
{
this.Salary=salary;
}
public String getinstructorName()
{
return instructorName;
}
public void setinstructorName(String instructorname)
{
this.instructorName=instructorname;
}
static void findStudents(Person[] person_array)
{
}
public String toString()
{
return instructorName + " is an instructor earning a salary of " + Salary;
}
}
////////////////////////////////////////////////////////////////////////////////
//CIS 459.23 Lab 2
//Due Oct 30 (Sunday)
//OSU wants you write some classes for their Personnel Record System. To make it simple,
//consider only 4 classes: Person, Employee, Instructor and Student. The following figure
//illustrates the relationship between these 4 classes. The Person class is the parent class of the
//Employee class and the Student class. The Employee class is the parent class of the Instructor
//class.
//The following are the tasks you need to complete for each of these classes.
// Create appropriate fields for each class. Necessary fields are listed. Add your own fields if
//needed. Some fields need to have appropriate constraint. Use your own way to make sure
//that these constraints are satisfied.
//o Person
//ID: int, starting from 1 and should be unique
//Name: String
//o Employee
//Salary: double and should not be negative
//o Student (For simplicity, assume that a student has at most 1 teacher)
//TeacherID: int. It’s his/her instructor's ID. 0 if no instructor is given
//TeacherName: String
//o Instructor:
// StudentIDArray: int array. An array of students’ IDs of this instructor. Set the
// array size to be 10, initially all 0s, assuming an instructor won’t have more than
// 10 students.
// All the above fields are private and only accessible through the access methods.
// A “toString()” method for each class to print out all the available information about the
// current object. In Person class “toString()” is declared as abstract.
// A static “findStudents(Person[] personArray)” method in the Instructor class to fill an
// instructor object’s students ID array, and the corresponding students’ TeacherID fields. See
// the test program for better understanding.
// Person should be declared as abstract class.
// Provide multiple constructors/methods if needed. Check the test.java program to see what
// constructors/methods are necessary and what actions they should do.
// If a class can use the parent class method and constructor, use “super” to call it to reduce the
// redundant code.
// Make sure this test.java program can work with your class.
// sample output. From this sample output, you’ll know what information you should print out
// for a specific object.
// NOTE: the sample output is not the unique output format of the test program. The real output
// format depends on how you design the toString() methods in each class. But make sure that your
// program will print out as much information about each object’s fields as possible, including the
// Person
// Instructor
// Employee Student
// inherited fields and the fields defined in its own class.
// HINT:
// o There is NO main method in any of these 4 classes
// o To make sure ID is unique across the objects, declare a static “LAST_ID” in the Person
// class.
// o Read descriptions in test.java VERY CAREFULLY for better
// understanding!
// Submit your Person.java, Emloyee.java, Student.java and Instructor.java files
// Appendix 1: Test Program
/*
* Lab 2 Program to test the Person, Employee, Student, and Instructor classes.
*/
public class Lab2_Test
{
public static void main(String[ ] args)
{
// uncommenting the following line should produce a compile error.
// This is for testing of an abstract class.
// Person p = new Person("George");
final int MAX_HEADCOUNT = 20;
Person[] person_array = new Person[MAX_HEADCOUNT];
// A student named Peter
person_array[0] = new Student("Peter");
// An instructor named Peter
person_array[1] = new Instructor("Peter");
// An instructor named Sandy and her salary
person_array[2] = new Instructor("Sandy", 25000);
// A janitor named Bob
person_array[3] = new Employee("Janitor Bob");
// A student named Tom and his instructor is Peter.
// The constructor needs to do three things:
// 1: sets this student’s “TeacherName” field to be “Peter”,
// 2: finds out the ID of the 1st instructor
// who exists in the person_array so far and named "Peter",
// and assign it to this student's “TeacherID” field.
// Set it to be 0 if no instructor named Peter is found in the person_array so far
// 3: records this student’s ID in the instructor’s StudentArray if such an instructor is found
// right after executing the following statement
// person_array[4].TeacherID = 2
// person_array[4].TeacherName = “Peter”
// person_array[1].StudentArray[0] = 5
person_array[4] = new Student("Tom", "Peter", person_array);
// A student named Maggie and her instructor is Susan
// right after executing the following statement
// person_array[5].TeacherID = 0
// person_array[5].TeacherName = “Susan”
person_array[5] = new Student("Maggie", "Susan", person_array);
// An instructor named Susan and her salary
person_array[6] = new Instructor("Susan", 40000);
// After all objects are created,
// instructors need to fill their students arrays,
// and some students need to fill their TeacherIDs now,
// since there may exist cases that when a Student object is created with instructor’s name,
// the corresponding Instructor object hasn’t been created and is not in the person_array.
// For example, person_array[6] is created after person_array[5].
// You need to record person_array[5]’s ID in person_array[6]’s studentArray field,
// and record person_array[6]’s ID in person_array[5]’s TeacherID field.
// Note: if there are more than one Instructor objects
// having the same names as a Student object’s TeacherName,
// it’ll always be the first one’s ID assigned to the Student object’s TeacherID
Instructor.findStudents(person_array);
System.out.println("ID and name of all personnel in the array");
for (int i = 0; i < Person.getMaxID(); i++)
{
System.out.println(person_array[i].getId() + ":" + person_array[i].toString());
}
}
You are trying to print using this:
for (int i = 0; i < Person.getMaxID(); i++)
{
System.out.println(person_array[i].getId() + ":" + person_array[i].toString());
}
But, the getMaxID() method in your Person class returns a hardcoded 0, so this loop will never iterate, and your print statement will never be reached.
EDIT: it makes no sense to even check for a maxId. Check against the length of the array:
for (int i = 0; i < person_array.length; i++)
{
System.out.println(person_array[i].getId() + ":" + person_array[i].toString());
}

How to set salary for object before adding it arraylist

Im reading data from a text file
which includes information about employees details
as the following:
H ,name ,socialNumber,hours,rate
S,name,social number,salary
and add them to tow lists.
If they are hourly employee:
H.add(new Hourly(name ,number,hour,rate);
Else if they were salaried:
S.add(new salaried(name,number);
The question is: how to add the salary for the employee before adding the object to the list?
hourly = rate*hours
Salaried = salary
I have attribute salary
and mutator method which sets double salary
I also set the salary after adding the object to the list,
but the took the last salary form the text
The first 1500 the second 2000
If you want to set the Salary before adding it to the List, you can define the new Entry before, change the Salary and then adding it:
Salaried s = Salaried(name,number);
s.setSalary(computedSalary);
S.add(s);
I hope that help you,
Regards
You may consider the builder pattern, which offers a flexible way of constructing objects:
public class Salaried {
String name;
String socialNumber;
Double salary;
...
public static class Builder {
String name;
String socialNumber;
Double salary;
public Builder(String name, String socialNumber) {
this.name = name;
this.socialNumber = socialNumber;
}
public Builder salary(Double salary) {
this.salary = salary;
return this;
}
public Salaried build() {
Salaried salaried = new Salaried(name, socialNumber);
salaried.setSalary(salary);
return salaried;
}
}
}
S.add(new Salaried.Builder("bob","12345678").salary(40000).build());

I need to create a map from an farm object list using the salary from Emploee class

This is the code I wrote so far for the other things I need to do. The main problem is that even with so much info I can't understand how to do it.
Create a map from the farm list which has like key the salary and like value the list of employee that has that salary. Display the map content, and for each employee display the farm in which is working
public class Employee implements Comparable<Employee> {
private String name;
private Integer salary;
public Employee (String name , Integer salary) {
this.name = name;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getSalary() {
return salary;
}
public String toString() {
return name + " " + salary;
}
public int compareTo(Employee emp) {
return this.salary.compareTo(emp.getSalary());
}
}
Farm class
public class Farm {
private String name;
private Integer surface;
List<Employee> emp = new ArrayList<Employee>();
public Farm(String name , Integer surface) {
this.name = name;
this.surface = surface;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSurface(Integer surface) {
this.surface = surface;
}
public int getSurface () {
return surface;
}
public String toString() {
return name + " " + surface;
}
public void makeList(String ename , Integer esalary) {
this.emp.add(new Employee(ename,esalary));
}
public void getList() {
for(Employee el : emp)
System.out.println(el);
}
public Employee getMostPaidEmployee() {
return Collections.max(emp);
}
}
And my main one
public static void main(String args[])
{
List <Farm> FarmList = new ArrayList<Farm>();
Farm farm1 = new Farm("Tiguana" , 700);
farm1.makeList("Mihai", 30000);
farm1.makeList("Vladimir", 4000);
farm1.makeList("Tusnic", 3000);
farm1.getList();
System.out.println(farm1.getMostPaidEmployee());
Farm farm2 = new Farm("Tipirei" , 800);
farm2.makeList("Mihai", 30000);
farm2.makeList("Mihail", 40000);
farm2.makeList("Armando", 50000);
farm2.makeList("ASihai", 60000);
System.out.println(farm2.getMostPaidEmployee());
FarmList.add(farm2);
FarmList.add(farm1);
}
Map< Integer , List< Employee > >
Sounds like you want to build a Map< Integer , List< Employee > >. The key, of type Integer (object, not primitive int), is the salary. The value is a List of employees with that particular salary.
So you need to instantiate such a Map, probably a HashMap, or perhaps a SortedMap such as TreeMap. Then as you loop the employees, you see if their salary has already been added as a key to the map. If not, add the salary as a key, and create an empty List object as the value. Add that particular employee to the new list. If the salary is already present, retrieve the list, add the employee.
To report by farm, you need to find which farm hired that employee. You will loop the keys of the map, for each key retrieve its list of employees, and then loop those employees. For each employee, loop all the farms, and retrieve each farm’s list of employees, and see if the target employee is in that list. If so, you know the farm of the employee in the list on the map.
One flaw in your code is defining a compareTo on Employee by salary. Intuitively we can tell that does not smell right. You should instead have an identifier on each employee, like most any company assigns an “employee id” to each person hired. For the sake of your exercise, I would just use a UUID as the id. Add a member field of type UUID to your Employee class. Define compareTo using that object.
As this is obviously homework, I think I have said enough. You should be able to figure this out following my prose. You can also search Stack Overflow for many many examples of maps with a list as the value, and other such issues.
In real work, we would likely be concerned with concurrency issues. But I assume that was not intended as part of your school assignment.
See also the coding-style tips I posted as Comments on the Question.
This is how you gonna do it :
Map<Integer, List<Employee>> map = new HashMap<>();
for(Farm f : FarmList){
for(Employee e : f.emp){
if(!map.containsKey(e.salary)){
map.put(e.salary, new ArrayList<>());
}
map.get(e.salary).add(e);
}
}
Be sure to add the field of FarmName to your employee and override toString() method in Employee class so you can display what's asked.

if there are two methods with same name in Parent class and Child Class ..?

If there are two methods with same name in Parent class and Child Class, for example:
Parent class:
public abstract class Employee implements Payments {
private String name;
protected double basicSalary;
public Employee(String name, double basicSalary) {
this.basicSalary = basicSalary;
this.name = name;
}
public void display() {
System.out.println( " Name: " + name + " - Basic Salary: " + basicSalary +"SR" );
}
}
Child class:
public class Faculty extends Employee {
private String degree;
private int teachingHours;
public Faculty(String name, double salary, String degree, int teachingHours) {
super(name, salary);
this.degree = degree;
this.teachingHours = teachingHours;
}
public void display() {
System.out.println( " Name: " +getName() + " - Degree:" +degree);
}
And I create an object like this:
Employee[] arrEm = new Employee[4];
arrEm[0] = new Faculty("ahmad", 1000, "Phd", 10);
So if I write
arrEm[0].display();
this way the method display() will be used in child. But in case we want to use the method display in Parent Class, how can it be done?
Thanks in advance !
This is because first you do:
Employee [] arrEm = new Employee [4];
this will make arrEm array for objects. Then you do this:
arrEm[0]= new Faculty("ahmad" , 1000 , "Phd" , 10 );
You use the arrEm[0] to refer a child class object so it will use display of the child. This is a normal case of polymorphism. You can search for it on google. It's useful. If you want to use the parent display use
arrEm[0] = new Employee;
or there is a way to upcast like
child a= new child();
Parent p=(Parent)a;
this a.display() will use the display in the parent class.
You have to call it as the following :
super.display();
Then either don't declare display method in child class or create instance of parent class instead of child class likerrEm[0]= new Employee("ahmad" , 1000 )(though i don't think you want this)or call parent method from child class like super.display()
If you want to call display method of parent class, you should add super.dislay() to display() method of Faculty class.
public class Faculty extends Employee {
private String degree;
private int teachingHours;
public Faculty( String name , double salary , String degree , int teachingHours)
{
super(name , salary );
this.degree=degree;
this.teachingHours = teachingHours;
}
public void display()
{
//calling display() method of parent class
Super.display();
System.out.println( " Name: " +getName() + " - Degree:" +degree);
}
or
If you do not want to call it from child class then create object using parent class constructor not child class.
Employee [] arrEm = new Employee [4];
//calling parent class constructor
arrEm[0]= new Employee("ahmad");
Here you can not make use of members of Faculty class(degree, teachingHours).

Calling child methods while using polymorphism in an arraylist

I have a small project that I'm working with inheritance and polymorphism. I have an ArrayList of type Employee that contains both Hourly and Salary employee objects. I would like to be able to use a for loop to call a calcPay function in the Hourly class provided the object in the ArrayList of type Employee is an Hourly employee. The line
System.out.println("Wage: " e.calcPay());
Gives the error The method calcPay() is undefined for type employee. How do you downcast the object? I've looked in a lot of forums and I couldn't find an option that would allow me to do it inline or without writing an abstract method that I'd have to include in all of the child classes of Employee. Any insight would be much appreciated.
public class Driver {
public static void main(String[] args) {
ArrayList<Employee> list = new ArrayList<Employee>();
Employee emp1 = new Hourly("Hourly Emp", "123 E Center", "555-555-5555", 00001, "123-45-6789", 12.75);
Employee emp2 = new Salary("Salary Emp", "123 E Center", "555-555-5555", 00001, "123-45-6789");
list.add(emp1);
list.add(emp2);
for(Employee e : list){
if(e instanceof Hourly)
{
System.out.println("Wage: " e.calcPay());
}
}
}
public abstract class Employee {
private String name, address, phone, ssn;
private int empNo;
Employee(String name, String address, String phone, int empNo, String ssn)
{
this.name = name;
this.address = address;
this.phone = phone;
this.empNo = empNo;
this.ssn = ssn;
}
}
public class Hourly extends Employee {
private double wage;
Hourly(String name, String address, String phone, int empNo, String ssn, double wage)
{
super(name, address, phone, empNo, ssn);
this.wage = wage;
}
public double calcPay(double hours)
{
return wage * hours;
}
}
Even though you are making sure e is of type Hourly, you still need to cast it and use Hourly type to call calcPay() because e is of type Employee and Employee is not aware of any calcPay() method because you have defined calcPay() as only Hourly class method.
if(e instanceof Hourly)
{
Hourly hourly = (Hourly)e;
System.out.println("Wage: " hourly.calcPay());
}
If you want calcPay() accessible for all Employee instances, you need to define calcPay() as abstract method in Employee class, then you can avoid casting.
Updated:
if(e instanceof Hourly)
{
System.out.println("Wage: " ((Hourly)e).calcPay());
}
If calcPay is supported for all Employees, then it should be an abstract method in Employee, which will let you call it without having to downcast at all.

Categories