Calling A Created Class In A Test Class In Java - java

I have created a public class: Employee. Now I would like to create a drive class to test this new class. However, I cannot figure out how to call my created class within the driver class: EmployeeTest. I have placed each class (Employee and EmployeeTest) in the same directory; however, I am still receiving the error message: "Cannot find class Employee."
Can anyone help me to get on the right track?
Here is my code for class Employee:
package employee;
/**
*
* #author ljferris
*/
public class Employee {
private String first; // Instance variable for first name
private String last; // Instance variable for last name
public double salary; // Instance variable for monthly salary
// Constructor initializes first with parameter firstName and intializes last with parameter lastName
public Employee(String firstName, String lastName){
this.first = firstName;
this.last = lastName;
}
// Constructor initializes salary with parameter monthlySalary
public Employee(double monthlySalary){
this.salary = monthlySalary;
}
// Method to set the first and last name
public void setName(String firstName, String lastName){
this.first = firstName;
this.last = lastName;
}
// Method to set the monthly salary
public void setSalary (double monthlySalary){
this.salary = monthlySalary;
if (salary > 0.0)
this.salary = monthlySalary;
}
// Method to retrive the first and last name
public String getName(){
return first + last;
}
// Method to retrive monthly Salary
public double getSalary (){
return salary;
}
} // End class Employee
Here is the code for EmployeeTest:
package employeetest;
/**
*
* #author ljferris
*/
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("Leviticus Ferris", 1200.00);
}

As per your code Employee and EmployeeTest are in different packages. You need to add import employee in EmployeeTest class. Then you can create new Employee instance from EmployeeTest.
package employeetest;
import employee;
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("Leviticus Ferris", 1200.00);
}
UPDATE For below comment:
Add one more constructor with firstName and salary as parameters.
public Employee(String firstName, double salary){
this.first = firstName;
this.salary = salary;
}
If you want 3 values to be intialized. Add one more constructor by taking all fields.
public Employee(String firstName, String lastName, double salary){
this.first = firstName;
this.last = lastName;
this.salary = salary;
}

Related

Accessing specific child type method in arraylist of type parent without typecasting, creation of child type is only known at runtime

I have the following parent class:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And 2 child class which extends parent:
public class FullTimeEmployee extends Employee {
private double salary;
public FullTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
}
public double getSalary() {
return salary*2;
}
}
public class PartTimeEmployee extends Employee {
private double salary;
public PartTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
}
public double getSalary() {
return salary;
}
}
The scenario:
I am using an ArrayList to contain information about employees. The ArrayList is created at the start of the program, and the type of employee being added into the Arraylist is a child extending parent and only known at runtime through user's input
public class EmployeeApplication {
public static void displayInfo(Employee employee) {
// How do I access the method getSalary() that belong to the specific type determined on runtime?
System.out.println(employee.getSalary()); // <--- ???
}
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Type of employee to add into arraylist: ");
String userInput = keyboardInput.nextLine();
// ArrayList to contain information about employees
ArrayList<Employee> employeeAL = new ArrayList<Employee>();
// Type of employee being created and added into ArrayList is dynamic and only known at run time based on user input
if(userInput.equals("full")) {
employeeAL.add(new FullTimeEmployee("John", 1000));
}
else {
employeeAL.add(new PartTimeEmployee("John", 500));
}
displayInfo(employeeAL.get(0));
keyboardInput.close();
}
}
Now the question:
how do I access the method getSalary() belonging to the specific child type that was determined on runtime? Since the object retrieved from the ArrayList is a parent type. Please note that the salary attribute only belongs to the child class.
My current implementation has me checking for the child type, typecasting it into that child type, and finally accessing the method belonging to the child.
I am trying to avoid typecasting because I believe I am doing things wrongly with regards to good Java coding practise. I'm missing something here but I just don't know what
Another method which I have thought about is to implement the method getSalary() in the parent class and overriding it in the child class, this way, I don't have to typecast but I don't know if this is the right practice since the salary attribute has got no relation with Employee at all:
// Parent
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
// ADDED THIS <----
public double getSalary() {
return 0.0;
}
}
// Child
public class FullTimeEmployee extends Employee {
private double salary;
public FullTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
}
// ADDED THIS <----
#Override
public double getSalary() {
return salary*2;
}
}
what am I doing wrongly and what is the best Java coding practice?
You can implement Employee as abstract and add getSalary() as an abstract method which forces subclasses of Employee to implement that method
public abstract class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
abstract protected double getSalary();
}

Java working with superclasses, but I do not get the output I expect

Hi I have written this program that Implements a superclass Employee that has the following fields and methods.
Fields:
String firstName
String lastName
int employeeID
double salary
Methods:
Constructor(): initialize balance field to null and zero.
Setters and getters for firstName, lastName, and employeeID
EmployeeSummary() – prints all account attributes
Part 2: Implement a Manager class that inherits from the Employee class.
Has a department attribute
Methods:
EmployeeSummary() – prints all superclass and subclass attributes
The problem is I expected to see:
Employee Name: Charles Dickens Employee Id : 34599 salary: 6500.0
Department : Accounts
as the output but I get nothing....
Any help is greatly appreciated.
here is the code:
package week1john_huber;
import java.util.*;
import java.lang.*;
import java.io.*;
class Employee {
//attributes of Employee class
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee() { //default constructor
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.0;
}
public void setFirstName(String fname) { //set and get methods for all attributes
firstName = fname;
}
public String getFirstname() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lname) {
lastName = lname;
}
public double getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int empId) {
employeeID = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double s) {
salary = s;
}
public void EmployeeSummary() { //display all attributes of Employee
System.out.println("Employee Name: " + firstName + " " + lastName + " Employee Id :" + employeeID + " salary: " + salary);
}
}
class Manager extends Employee {
private String department;
public Manager() { //default constructor
super(); //calling superor base class default constructor
department = null;
}
public String getDepartment() {
return department;
}
public void setDepartment(String dept) { //set and get methods for department
department = dept;
}
public void EmployeeSummary() {
super.EmployeeSummary(); //calling super class method with same name
System.out.println("Department : " + department);
}
}
class TestEmployee {
public static void main(String[] args) {
Manager mgr = new Manager();
mgr.setFirstName("Charles"); //all set methods of super class are available to derived class
mgr.setLastName("Dickens");
mgr.setEmployeeID(34599);
mgr.setSalary(6500);
mgr.setDepartment("Accounts");
mgr.EmployeeSummary();
}
}
Ok, I believe the problem is the fact that you have the whole thing in a single file.
Try moving the TestEmployee class to its own file and rename the class to
public class TestEmployee
It should work that way.

How to add new Employee without declaring a lot of object names

I have a small assignment on adding and displaying different types of employees(diff. departments) at work and different salary & benefits, using OOP approach. I am quite not sure if my code is correct in terms of code reuse & if did I really meet the OOP coding approach...So far I have displayed 1 employee each type/department, I made them as a class name.(see code below). My question is if I add a new employee I'm going to declare another object of type Employee again. And what if there will be a lot of employees, I will be having a lot of objects. How do I lessen that and may I know if my OOP coding approach is correct so far? Ty very much! Here is my code:
//this is my parent class which implements an interface...
public abstract class Employees implements ICompensation{
private String fname;
private String lname;
private char gender;
private String address;
private double salary;
public String getfname(){
return this.fname;
}
public void setfname(String fname){
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
// this is a Developer type of employee
public class Developer extends Employees{
public Developer(String fname,String lname, char gender,String address, double salary){
setfname(fname);
setLname(lname);
setGender(gender);
setAddress(address);
setSalary(salary);
}
#Override
public double calculateSalary() {
double salary = getSalary();
salary += 10;
return salary;
}
#Override
public void print() {
System.out.println(this.getClass());
System.out.println(this.getfname());
System.out.println(this.getLname());
System.out.println(this.getGender());
System.out.println(this.getAddress());
System.out.println(this.calculateSalary());}}
//this is QA type of employee
public class QA extends Employees{
public QA(String fname,String lname,char gender,String address,double salary) {
setfname(fname);
setLname(lname);
setGender(gender);
setAddress(address);
setSalary(salary);
}
#Override
public double calculateSalary() {
double salary = getSalary();
salary = salary + 20;
return salary;
}
#Override
public void print() {
System.out.println(this.getClass());
System.out.println(this.getfname());
System.out.println(this.getLname());
System.out.println(this.getGender());
System.out.println(this.getAddress());
System.out.println(this.calculateSalary());
}
}
I have another 2 classes which are BA & Manager class but I wont include here because it's just have the same contents to the other derived class.
//so here is my Interface
public interface ICompensation {
double calculateSalary();
void print();
}
//and here is my main method.
import java.util.*;
public class main {
public static void main(String[] args){
Employees dev = new Developer("Janel","Logrono",'M',"Alabang",491);
Employees qa = new QA("juan","Sir",'M',"Taguig",1240);
Employees ba = new BA("pedro","Lyn",'F',"Taguig",1150);
Employees manager = new Manager("sebastian","rods",'M',"USA",555399);
ArrayList<Employees> ls = new ArrayList<>();
ls.add(dev);
ls.add(qa);
ls.add(ba);
ls.add(manager);
for(Employees e : ls){
e.print();
System.out.println();
}
}
}
How do add another employee w/o declaring a lot of objects and may I know if my OOP coding approach is correct so far, I think there are a lot of redundant codes here, how to lessen it? thx!
First of all you should not implements ICompensation in the bean class. Bean class will only contain getters, setters & constructor. You need to create another class which will implement the ICompensation. There you will write the code for calculations and other methods.
In database you can add another column "Role" which will define the employee role. By this approach you don't need to create extra methods such as QA, Developer, Manager.
please look into the following link. Here they tried to develop a login page using MVC model. You can just ignore the jsp pages and concentrate on controllers and beans.
https://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern

How to pass variables between classes?

I am very new to Java and have searched through previously asked questions which haven't helped my issue...
How do I pass the int variable age, and the String name, from the main class to the Person class?
package engineers;
import java.util.Scanner;
public class Engineers {
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in); //declaration and ssignment of scanner
System.out.println("Enter name: "); //name prompt
String name = scan.next(); //reads name input from user
System.out.println("Enter age: "); //age prompt
int age = scan.nextInt(); //reads age input from user
System.out.println("Pay check amount: ");
double salary = scan.nextDouble();
Person person = new Person();
}
private static class Person {
/**
* A default constructor
*/
public Person() {
}
/**
* method for displaying the computation result
*/
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * age + 0.141) );
public void showData(int age, double pay){
System.out.printf( "%s earns $%4.3f for age %3d.\n", name, (pay*Math.sqrt(age)*.15), age);
}//end method showData
}
}
You should use Person constructor like this:
public Person(int age, String name) {
this.age = age;
this.name = name;
}
And add two fields in your Person class, before your constructor:
private int age;
private String name;
Then I am assuming you need to use this variables inside the person class, in order to do this, you can do something like this:
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * this.age + 0.141) );
To reference your variable:
public void showData(){
System.out.printf( "%s earns $%4.3f for age %3d.\n", this.name, (pay*Math.sqrt(this.age)*.15), this.age);
}//end method showData
Finnaly, you need to instantiate your Person object to use it:
Person p = new Person(name, age);
I would also recommend (since you are learning java), to understand the difference between getters/setters and constructor approach: Setter methods or constructors
You mean something like this?
int age;
String name;
class Person(int age, String name) {
this.age = age;
this.name = name;
}
Or (And)
void setAge(int age) {
this.age = age;
}
void setName(String name) {
this.name = name;
}
You would want to define a constructor with any argument another class may need for the most basic functioning.
A Person istance would be initialized with a name and age (even though It would be better to store a birth date and calculate the age against the current date).
To do this, you'd need the class Person to look like this:
public class Person{
private String name;
private Date birthdate;
//Constructor method
public Person(String n, Date bd){
name=n;
birthdate=bd;
}
//Other methods
}
In the main() method, you would then create a new istance of Person, after getting anything needed, like this:
Person p = new(name, date);

First time using methods and constructors in JAVA, recieving errors in a program to determine raises

I'm coding a fairly simple program that simply outputs 2 employee's Names, their salary, and a 10% raise to that salary.
I have 2 issues: 1) The salary prints as '$0.000000' 2) Ii cannot get the raise method to work properly
Here's my code:
public class Employee {
// instance variable
private String name;
private String lastName;
private double salary;
// setters
public String getLastName() { return lastName; }
public String getName() { return name; }
public double getSalary() { return salary; }
public void raise(double raise) { salary = salary + (salary * .1); }
// getters
public Employee(String name, String lastName, double salary) {
this.name = name;
this.lastName = lastName;
if (salary > 0.0) {
this.salary = salary;
}
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee raise1 = new Employee("Betty", "Jones", 4000.0);
Employee raise2 = new Employee("Sally", "Mae", 6000.0);
// Print statements for the employee's name and salary
System.out.printf("Employee #1\nFirst Name: %s\nLast Name: %s\n\n" + "Salary: $%f", raise1.getName(), raise1.getLastName(), raise1.getSalary());
// THIS IS WHERE I'M HAVNG TROUBLE
System.out.printf("Her raise will be: %d", raise1.raise(salary));
System.out.printf("Employee #1\nFirst Name: %s\nLast Name: %s\n\n" + "Salary: %f", raise1.getName(), raise1.getLastName(), raise1.getSalary());
raise2.raise(salary);
}
}
Thanks in advance for the help!
The reason salary printed $0.00000 is because you've placed if statement for some reason instead of just setting salary you passed to constructor. Second thing, void methods does not return anything that's the reason raise method did not work the way you wanted. I fixed it for you so take a look, hopefully I helped you understand where you went wrong and if you have any questions feel free to ask I'm here for you.
Employee Test class:
public class EmployeeTest {
public static void main(String[] args) {
Employee raise1= new Employee("Betty","Jones",4000.0);
Employee raise2= new Employee("Sally","Mae",6000.0);
//Print statements for the employee's name and salary
System.out.printf("Employee #1\nFirst Name: %s\nLast Name: %s\n\n" +
"Salary: $%.2f",
raise1.getName(),
raise1.getLastName(),
raise1.getSalary());
System.out.printf("\nHer raise will be: $%.2f",
raise1.raise(raise1.getSalary()));
System.out.printf("\n\nEmployee #2\nFirst Name: %s\nLast Name: %s\n\n" +
"Salary: $%.2f",
raise2.getName(),
raise2.getLastName(),
raise2.getSalary());
System.out.printf("\nHer raise will be: $%.2f\n",
raise2.raise(raise2.getSalary()));
}
}
Employee class:
public class Employee {
//instance variable
private String name;
private String lastName;
private double salary;
//getters
public String getLastName() {
return lastName;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public double raise(double raise){
salary = salary + (salary*.1);
return salary;
}
//constructor
public Employee(String name, String lastName, double salary){
this.name = name;
this.lastName = lastName;
this.salary = salary;
}
}
Print output from the program above:
Employee #1
First Name: Betty
Last Name: Jones
Salary: $4000.00
Her raise will be: $4400.00
Employee #2
First Name: Sally
Last Name: Mae
Salary: $6000.00
Her raise will be: $6600.00
When you do
Employee raise1= new Employee("Betty","Jones",4000.0);
you call the constructor of Employee class that have the following condition:
if (salary <0.0){
this.salary = salary;
}
Since 4000.0 is more than 0, it never gets assigned.
Your raise() method's return type is void, which means that it will not return anything at all. Change the return type to double, and simply typing return this.salary at the end should work fine. It should look like this:
public double raise(double salary)
{
this.salary = salary + (salary * 0.1);
return this.salary;
}
The this keyword references the instance of the object that you are using. Put it simply, you probably want to reference the classes salary variable, rather than the parameter passed in the method, otherwise it will reference the parameter passed in.
And you also need call this.salary = salary; in your constructor, because the only way it was assigned before is if salary is below zero, but 4000 is not below zero.

Categories

Resources