I have a problem passing params into a super constructor. I'm implementing Abstraction with Inheritance. I created three classes that extends the abstract class Employee. But when I created the objects of these three classes, only one class passes the arguments correctly to the super() constructor, while the rest will return null.
Here is the abstract class
public abstract class Employee {
private String firstName,lastName,SSN;
public Employee(String fName, String lName, String SSN){
this.SSN = SSN;
this.firstName = fName;
this.lastName = lName;
}
public void setFirstName(String fName){
this.firstName = firstName;
}
public void setLastName(String lName){
this.lastName = lName;
}
public void setSSN(String SSN){
this.SSN = SSN;
}
public String getSSN(){
return SSN;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public abstract double getEarnings();
#Override
public String toString(){
return String.format("First Name: %-2s \n Last Name: %-2s \n Social Security Number: %-2s", getFirstName(), getLastName(),getSSN());
}
And here are the classes:
public class SalariedEmployee extends Employee {
private String firstName, lastName, SSN;
double weeklyPay;
public SalariedEmployee(String fName, String lName, String SSN, double wPay) {
super(fName, lName, SSN);
this.weeklyPay = wPay;
}
public void setWeeklyPay(double wPay) {
this.weeklyPay = wPay;
}
public double getWeeklyPay() {
return weeklyPay;
}
#Override
public double getEarnings() {
return getWeeklyPay();
}
#Override
public String toString() {
return String.format("%s \n Weekly Pay: %2s", super.toString(), getEarnings());
}
}
public class HourlyEmployee extends Employee{
private String firstName, lastName, SSN;
private double hourlyPay,wage;
private int hours;
public HourlyEmployee(String fName, String lName, String SSN, int hour, double hourlyPay ){
super(fName, lName, SSN);
this.hours = hour;
this.hourlyPay = hourlyPay;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSSN() {
return SSN;
}
public void setSSN(String SSN) {
this.SSN = SSN;
}
public double getHourlyPay() {
return hourlyPay;
}
public void setHourlyPay(double hourlyPay) {
this.hourlyPay = hourlyPay;
}
public double getWage() {
return wage;
}
public void setWage(double wage) {
this.wage = wage;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
#Override
public double getEarnings(){
double earnings;
if(hours> 40)
earnings = hourlyPay * 40 + ((hours-40) *hourlyPay *1.5);
else
earnings = hourlyPay * hours;
return earnings;
}
#Override
public String toString(){
return String.format("%s \n Hours worked: %s \n Salary: %s \n ", super.toString(), getHours(), getEarnings());
}
}
public class CommissionEmployee extends Employee {
private String firstName, lastName, SSN;
private double sales,commission;
public CommissionEmployee(String fName, String lName, String SSN, double sales, double commission){
super(fName, lName, SSN);
this.commission = commission;
this.sales = sales;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSSN() {
return SSN;
}
public void setSSN(String SSN) {
this.SSN = SSN;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
public double getCommission() {
double commissionRate;
if(commission >0 && commission<1)
return commission;
else
return 0;
}
public void setCommission(double commission) {
this.commission = commission;
}
#Override
public double getEarnings(){
return getCommission() * getSales();
}
#Override
public String toString(){
return String.format("%s \n Commission Rate: %s \n Salary: %s \n", super.toString(), getCommission(), getEarnings());
}
}
And Here is the TEST Class
public class EmployeeTest {
public static void main(String[] args) {
Employee salariedEmp,hourlyEmp,commissionEmp;
salariedEmp = new SalariedEmployee("Aminu", "Bishir", "11-22-33-33", 300.47);
System.out.println(printDetails(salariedEmp));
hourlyEmp = new HourlyEmployee("Musa","Sale","22-33-44-55",50,20.4);
System.out.println(printDetails(hourlyEmp));
commissionEmp = new CommissionEmployee("Muhammad","Ibrahim","33-44-55-66",20000,0.3);
System.out.print( printDetails(commissionEmp));
}
public static String printDetails(Employee emp){
return String.format("%s \n %s",emp.getClass(),emp.toString());
}
}
And this is the output I get whenever I run it:
class Abstraction.SalariedEmployee
First Name: Aminu
Last Name: Bishir
Social Security Number: 11-22-33-33
Weekly Pay: 300.47
class Abstraction.HourlyEmployee
First Name: null
Last Name: null
Social Security Number: null
Hours worked: 50
Salary: 1122.0
class Abstraction.CommissionEmployee
First Name: null
Last Name: null
Social Security Number: null
Commission Rate: 0.3
Salary: 6000.0
You should delete line
private String firstName, lastName, SSN;
In child classes CommissionEmployee, HourlyEmployee and SalariedEmployee. Because these properties are declared in your abstract class Employee, use it.
You have a problem with declaring variables multiple times. By declaring them in a super class, they also get declared in a subclass. When you declare the variables with the same name in a subclass, you can address the superclass' variable via super.variable. But I would recommend you to simply delete the variable declarations in your subclasses, that were already declared in the superclass.
However this is not the root of your problem. A similar issue occures if you override methods, in your case the subclass that prints correctly does not override the getters, which are used to read out the information stored in your variables. In the class that prints out correctly the getters are found in the superclass and hence the getters are addressing the superclass variables. In the other 2 classes the overridden getters are found, that are using the variables found in the subclasses. Since you set only the variables in the superclass, the subclass variables are always null and so is your result.
I would recommend you to delete the overriden getters and the variables in the subclasses. You don't need them.
Variables
private String firstName,lastName,SSN;
are already defined in your employee class, no need to repeat them. That's why of those nulls
Related
New to Java!
I have created a class that has constructors for various fields. However, when I try and print the fields, I recieve "null" as the output. Please help me understand why. Here is the class:`
public class User {
//All relevant information to identify each user.
private String FirstName;
private String LastName;
private String Email;
private long PhoneNum;
private long CardNum;
//Build Constructors for User info.
public User(String Fname, String Lname, String Mail, long num, long card)
{
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
//Method to set FirstName.
public void setFirstName (String Fname)
{
FirstName=Fname;
}
//Method to get FirstName.
public String getFirstName()
{
return FirstName;
}
//Method to set LastName.
public void setLastName (String Lname)
{
LastName=Lname;
}
//Method to get Lastname.
public String getLastname()
{
return LastName;
}
//Method to set email.
public void setEmail (String Mail)
{
Email=Mail;
}
//Method to get email.
public String getEmail()
{
return Email;
}
//Method to set phonenumber.
public void setPhoneNum(long num)
{
PhoneNum=num;
}
//Method to get phonenumber.
public long getPhoneNum()
{
return PhoneNum;
}
//Method to set credit card number.
public void setCardNum(long card)
`enter code here`{
CardNum=card;
}
// Method to get credit card number.
public long getCardNum()
{
return CardNum;
}
Now when I run this code, I receive "null":
public class UserDemo {
public static void main(String[] args)
{
String first="Matt";
String last="Burns";
String email="mburns267#yahoo.com";
long phone=333;
long card=222;
User Matt=new User(first,last,email,phone,card);
System.out.print(Matt.getLastname());
}
What am I doing wrong? Thank you in advance!
`
Is the other way around, instead of:
public User(String Fname, String Lname, String Mail, long num, long card){
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
it should be:
public User(String Fname, String Lname, String Mail, long num, long card){
FirstName = Fname;
LastName = Lname;
Email = Mail;
PhoneNum = num;
CardNum = card;
}
To avoid this kind of thing you can use the this keyword. Here is an example:
String firstName;
public Constructor(String firstName){
this.firstName = firstName;
}
You have your constructor assignments the wrong way:
public User(String Fname, String Lname, String Mail, long num, long card)
{
// this refers to the current object being constructed
this.FirstName = Fname;
this.LastName = Lname;
this.Email = Mail;
this.PhoneNum = num;
this.CardNum = card;
}
Java constructor objects should be created like so:
public User(String Fname, String Lname)
{
this.firstName = Fname;
//keyword 'this' refers to the new object, so the new object's Fname would equal the firstName place below
this.lastName = Lname; //same as above
}
To create a new User, use this code:
User Matt = new("Matt", "Burns"); //Creates a new User Matt, with firstName "Matt" and lastName "Burns"
System.out.println(Matt.getfirstName()); //prints User Matt's firstName to the console.
Summary:
New to Java, tried looking through other posts but didn't find an answer. I'm learning inheritance and have an AddressBook class extended by a Runner class. When I write a program to test the inheritance I create a Runner object. If I get the first String parameter it returns fine but when I attempt to get the second String parameter it returns null.
Question:
Why is the second parameter returning null?
package Assignment_1;
//Begin Class Definition
public class AddressBook {
// Member variables
private String businessPhone;
private String cellPhone;
private String facebookId;
private String firstName;
private String homeAddress;
private String homePhone;
private String lastName;
private String middleName;
private String personalWebSite;
private String skypeId;
//Constructors
public AddressBook (String firstName, String middleName, String lastName, String homeAddress, String businessPhone, String homePhone, String cellPhone, String skypeId, String facebookId, String personalWebSite) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.homeAddress = homeAddress;
this.businessPhone = businessPhone;
this.homePhone = homePhone;
this.cellPhone = cellPhone;
this.skypeId = skypeId;
this.facebookId = facebookId;
this.personalWebSite = personalWebSite;
}
public AddressBook (String firstName) {
this.firstName = firstName;
}
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
public AddressBook (String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Getters and setters
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getHomeAddress() {
return homeAddress;
}
public String getBusinessPhone() {
return businessPhone;
}
public String getHomePhone() {
return homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public String getSkypeId() {
return skypeId;
}
public String getFacebookId() {
return facebookId;
}
public String getPersonalWebsite() {
return personalWebSite;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public void setBusinessPhone(String businessPhone) {
this.businessPhone = businessPhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public void setSkypeId(String skypeId) {
this.skypeId = skypeId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public void setPersonalWebSite(String personalWebSite) {
this.personalWebSite = personalWebSite;
}
// Public methods
public static void compareNames(String name1, String name2) {
if(name1.equals(name2)) {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names are the same.");
} else {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names appear to be different.");
}
}
************************************************************
package Assignment_1;
public class BanffMarathonRunner extends AddressBook {
// Member variables
private int time;
private int years;
// Constructors
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
time = min;
years = yr;
}
// Getters and Setters
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}
************************************************************
package Assignment_1;
import Assignment_1.BanffMarathonRunner;
public class TestBanffMarathonRunner {
public static void main(String[] args) {
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
System.out.print(r1.getLastName());
}
}
}
Because lastName is null.
You are calling AddressBook(String firstName, String middleName)
and setting the middleName, not the lastName.
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
calls:
// firstName = "Elena"
// lastName = "Brandon"
// min = 341
// yr = 1
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
// ...
}
which calls via super(...):
// firstName = "Elena"
// middleName = "Brandon" <-- here is your issue
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
Brandon is set in AddressBook#middleName instead of AddressBook#lastName.
Your problem is in the BanffMarathonRunner.java:
in the constructor when you are calling the
super(firstName, lastName);
Actually by the call above the super class constructor with two parameter is being called, and that constructor is the one which set the middleName not the lastName.
I think you are confused because of the lastName variable name, which is passed to the constructor with two argument and that constructor use the second argument to set the middleName.
Good Luck.
I am implementing a payroll system in which I need to implement a PayrollSystem class to add an employee to an ArrayList of employees and create checks for each of those said employees. I've written up the Employee and Paycheck classes, but I'm having trouble with the PayrollSystem class.
How do I create the addEmployee method? Do I pass an Employee object to it along with the information on that employee or is there another way?
Employee:
package payrollSystem;
public class Employee {
private String firstName;
private String lastName;
private int ID;
private double hourlyWage;
private double hoursWorked;
public Employee(String first, String last, int id, double wage, double hours) {
firstName = first;
lastName = last;
ID = id;
hourlyWage = wage;
hoursWorked = hours;
}
public void setFirstName(String first) {
this.firstName = first;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String last) {
this.lastName = last;
}
public String getLastName() {
return lastName;
}
public void setID(int ID) {
this.ID = ID;
}
public int getID() {
return ID;
}
public void setHourlyWage(double hourlyWage) {
this.hourlyWage = hourlyWage;
}
public double getHourlyWage() {
return hourlyWage;
}
public void setHoursWorked(double hoursWorked) {
this.hoursWorked = hoursWorked;
}
public double getHoursWorked() {
return hoursWorked;
}
public double calcPay(double wage, double hours) {
wage = getHourlyWage();
hours = getHoursWorked();
return wage * hours;
}
}
PayCheck:
package payrollSystem;
public class PayCheck {
private String firstName;
private String lastName;
private int ID;
private double netAmount;
public PayCheck(String first, String last, int id, double wage, double hours) {
firstName = first;
lastName = last;
ID = id;
netAmount = wage * hours;
}
public String toString() {
return "Paycheck issued for " + netAmount + "to " + firstName + ", "+ lastName + ", employee ID " + ID;
}
}
PayrollSystem:
package payrollSystem;
import java.util.List;
import java.util.ArrayList;
public class PayrollSystem {
public List<Employee> employees = new ArrayList<Employee>();
public String companyName;
PayrollSystem(String company) {
companyName = company;
}
void addEmployee(Employee a) {
employees.add(a);
}
void getHoursWorked(double hrs) {
this.a.getHoursWorked();
}
void issueCheck() {
double checkAmount = this.a.calcPay(a.getHoursWorked(), a.getHourlyWage());
PayCheck check = new PayCheck(a.getFirstName(), a.getLastName(), a.getID(), a.getHoursWorked(), a.getHourlyWage());
check.toString();
}
}
You can make an addEmployee() method. As long as somewhere you create the employee, and then pass it into your payRoll class.
Would look like this, assuming you have a List of Employees :
public void addEmployee(Employee employee){
employees.add(employee);
}
In your main you could then just go (assuming myEmployee is an Employee Object):
PayrollSystem payrollSystem = new PayRollSystem();
payrollSystem.addEmployee(new Employee("John", "Smith", 1, wage, hours)); // Way 1
payrollSystem.addEmployee(myEmployee); // Way 2
The Employee Object will contain all the information of the Employee. So when that Object is passed in, all the information will come with it. That allows you to fetch all the Employees from the payrollSystem, or use internal methods to perform actions on them.
Please help me find errors from this code. I'm still new and I don't know if this is correct or not.
I do have one error.
This is the error:
constructor Person in class Person cannot be applied to given types;
super();
^
required: String,String,String
found: no arguments
reason: actual and formal argument lists differ in length
This is my code:
import java.util.*;
public class Person {
//Data fields
private String lastName;
private String middleInitial;
private String firstName;
//Constructors
public Person(String lastName, String middleInitial, String firstName) {
this.lastName = lastName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
//Accessor methods
public String getlastName() {
return lastName;
}
public String getmiddleInitial() {
return middleInitial;
}
public String getfirstName() {
return firstName;
}
//Mutator methods
public void setlastName(String lastName) {
lastName = lastName;
}
public void setmiddleInitial(String middleInitial) {
middleInitial = middleInitial;
}
public void setfirstName(String firstName) {
firstName = firstName;
}
public String getName() {
String studentName = this.lastName + ", " + this.firstName +
this.middleInitial + ".";
return studentName;
}
} //end Person class
class Address {
//Data fields
private String streetName;
private int zipCode;
private String state;
private String country;
//Constructors
public Address(String streetName, int zipCode, String state,
String country) {
this.streetName = streetName;
this.zipCode = zipCode;
this.state = state;
this.country = country;
}
//Accessor methods
public String getstreetName() {
return streetName;
}
public int getzipCode() {
return zipCode;
}
public String getstate() {
return state;
}
public String getcountry() {
return country;
}
//Mutator methods
public void setstreetName(String streetName) {
streetName = streetName;
}
public void setzipCode(int zipCode) {
zipCode = zipCode;
//Integer.toString(zipCode);
}
public void setstate(String state) {
state = state;
}
public void setcountry(String country) {
country = country;
}
public String getAddress() {
String studentAddress = streetName + "\n" + state + ", " + country +
"\n" + zipCode;
return studentAddress;
}
} //end Address class
class Student extends Person {
private String dateOfBirth;
//Constructors
public Student (String studentName, String dateOfBirth) {
super();
dateOfBirth = dateOfBirth;
}
//Accessor methods
public String getdateOfBirth() {
return dateOfBirth;
}
//Mutator methods
public void setdateOfBirth() {
this.dateOfBirth = dateOfBirth;
}
public String toString() {
return ("Date of Birth: " + dateOfBirth);
}
} //end Student subclass
Edited: If I do so for both the Person and Address class. I can only have three-arg constructors. How can I call a one-arg constructor?
For example, I have
public Student (String firstName, String lastName, String middleInitial, String dateOfBirth) {
super(firstName, lastName, middleInitial); and
public Student (String streetName, String state, String country) {
super(streetName, state, country);
How can I get zipcode separately?
Class Person has a constructor, therefore the default no-arg constructor is not created for you. Therefore you can't call super() in Student's constructor, you have to call super(lastName, middleInitial, firstName);.
Or you could create a new Person no-arg constuctor.
Try this
In student class
public Student ( String lastName, String middleInitial, String firstName,String studentName, String dateOfBirth) {
super( lastName, middleInitial,firstName);
this.dateOfBirth = dateOfBirth;
}
Or
In Person class create no arg consructor. Eg:
public Person(){}
Person Class has a constructor with arguments. So default constructor will not be created. So you have to pass 3 String parameters in super(3 String parameters) or you have to create a constructor which does not take any parameter in person class.
Recently I am doing a coding exercises I need to make my project , and so far I am practicing it with the code below what I want to ask is that, is this a has a relationship? am I doing the right practice? look at my code, sorry for my bad english
public class Personal {
private String firstName;
private String middleInitial;
private String lastName;
private int age;
public Personal(String firstName,String middleInitial , String lastName , int age){
setFirstName(firstName);
setMiddleInitial(middleInitial);
setLastName(lastName);
setAge(age);
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setMiddleInitial(String middleInitial){
this.middleInitial = middleInitial;
}
public String getMiddleInitial(){
return middleInitial;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getLastName(){
return lastName;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public String toString(){
return String.format("First Name: "+getFirstName()+"\nMiddle Initial: "+getMiddleInitial()+
"\nLast Name: "+getLastName()+"\nAge: "+getAge());
}
}
Contact Class
public class Contact {
private String address;
private String email;
private String contactNumber;
public Contact(String address,String contactNumber, String email){
setAddress(address);
setContactNumber(contactNumber);
setEmail(email);
}
public void setAddress(String address){
this.address = address;
}
public String getAddress(){
return address;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setContactNumber(String contactNumber){
this.contactNumber = contactNumber;
}
public String getContactNumber(){
return contactNumber;
}
public String toString(){
return String.format("Address: "+getAddress()+"\nContact Number: "+getContactNumber()+
"\nEmail Address: "+getEmail());
}
}
Employee Class
public class Employee {
private Personal personal;
private Contact contact;
public Employee(Personal personal, Contact contact){
this.personal = personal;
this.contact = contact;
}
public void setFirstName(String firstName){
this.personal.setFirstName(firstName);
}
public String toString(){
return String.format(personal.toString()+contact.toString());
}
}
And the Test class
public class TestClass {
public static void main(String[] args){
Personal personalHerp = new Personal("John","M","Doe",18);
Contact contactHerp = new Contact("88 Herp Derp St U mad New york","724-15-70","fido.com");
Employee employeeHerp = new Employee(personalHerp,contactHerp);
System.out.println(employeeHerp);
}
}
Well, since Employee doesn't extend Personal it has a Personal and a Contact.
I guess you'd rather like Employee to be a Personal and thus it should look like this:
public class Employee extends Personal {
private Contact contact;
...
}
So to summarize:
is-a means a class/object extends another class or implements an interface, i.e. A is-a B if A extends B or A implements B
has-a means that a class/object has a variable of that type, like Contact contact in your Employee class, which means Employee has-a contact.
Yes, this is a "has-a" relationship (exactly as we discussed in your other question).