I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.
staff[3].awardBonus(bonus);
I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;
import java.util.Scanner;
public class Tester
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
StaffMember[] staff = new StaffMember[4];
String internName = "Susan 2";
String empName = "Tyler O.";
String hrName = "Becky R.";
String execName = "Daniel H.";
String address = "Brighton";
String phone = "420 - 0000";
String SSN = "12345789";
double rate = 1000;
staff [0] = new Intern(internName, address, phone);
staff [1] = new Employee(empName, address, phone, SSN, rate);
staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
staff [3] = new Executive(execName, address, phone, SSN, rate);
for (StaffMember staffPrint : staff)
{
System.out.println (staffPrint.toString() + "\n");
}
System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
int input = scan.nextInt();
if(input == 1)
{
double bonus = 0;
System.out.println("Enter the bonus for your employee: ");
bonus = scan.nextDouble();
}
}
Here is the Executive class, Employee class and the StaffMember class
public class Executive extends Employee
{
public Executive(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone, SSN, rate);
}
public double pay()
{
double money = super.pay();
return money;
}
public String toString()
{
String employee = super.toString();
return employee;
}
public void awardBonus(double execBonus)
{
rate += execBonus;
}
}
Employee
public class Employee extends StaffMember
{
String SSN;
double rate;
public Employee(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone);
this.SSN = SSN;
this.rate = rate;
}
public double pay()
{
return rate;
}
public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
return employee;
}
}
StaffMember
public abstract class StaffMember
{
String name;
String address;
String phone;
public StaffMember(String name, String address, String phone)
{
this.name = name;
this.address = address;
this.phone = phone;
}
public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
return employee;
}
public abstract double pay();
}
staff is a StaffMember array. When you reference any item from it (as you do it staff[3]), you get a StaffMember.
StaffMember does not have a method awardBonus().
Your problem is that you are trying to call an undefined method on your StaffMember object. In fact the method awardBonus() was not defined in your StaffMember class.
And in the code staff[3].awardBonus(bonus) you were trying to call awardBonus() on staff[3] which is a StaffMember instance.
By providing an awardBonus for all StaffMembers, you can call it on a StaffMember. For instance:
public abstract class StaffMember
{
public void awardBonus(double bonus) {
if (bonus > 0) {
throw new IllegalStateException("Only executives receive a bonus");
}
}
...
public class Executive extends StaffMember
{
#Override
public void awardBonus(double bonus) {
P.S. be careful to inform the company on this.
You can use:
// Check if staff[3] is really an Executive
if(staff[3] instanceof Executive) {
// Cast staff[3] to an Executive
Executive executive = ((Executive)staff[3]);
// Now you can call awardBonus
executive.awardBonus(bonus);
}
Because staff is an StaffMember-array which doesn't contains the methode awardBonus.
You know that staff[3] is an Executive, but your program doesn't. Therefore you have to check if staff[3] is an instanceof Executive so you can safely cast it to an Executive with Executive executive = (Executive)staff[3].
Related
I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.
I am getting a syntax error in my main class when I call the constructor from another class that I need for the main program to run. This program is focused on inheritance and the appropriate calling of constructors and arguments. This is the error message I get during compilation:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "public", record expected after this token
at a6main.main(a6main.java:7)
This is the line of code that is causing the error:
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
"2000", true, "1000");
The rest of the code can be found below:
class person {
String Name;
String Address;
String Telephone;
person (String Name, String Address, String Telephone) {
this.Name = Name;
this.Address = Address;
this.Telephone = Telephone;
}
String getName() {
return Name;
}
String getAddress() {
return Address;
}
String getTelephone() {
return Telephone;
}
void setName(String Name) {
this.Name = Name;
}
void setAddress(String Address) {
this.Address = Address;
}
void setTelephone(String Telephone) {
this.Telephone = Telephone;
}
}
public class customer extends person {
String number;
boolean OnMailingList;
//constructor and getters and setters
customer (String Name, String Address, String Telephone, String number, boolean OnMailingList) {
//inherit persons information
super(Name, Address, Telephone);
this.number = number;
this.OnMailingList = OnMailingList;
}
String getnumber() {
return number;
}
void setnumber(String number) {
this.number = number;
}
boolean OnMailingList () {
return OnMailingList;
}
void setOnMailingList(boolean OnMailingList) {
this.OnMailingList = OnMailingList;
}
}
public class PreferredCustomer extends customer {
private int purchase;
double discount;
/**public constructor so its accessible to main
* else ifs for certain percentage of discounts
* getters and setters for purchase and discount
* super to inherit other features from other classes */
public int getpurchase() {
return purchase;
}
public double getdiscount () {
return this.discount;
}
public void setPurchase(int purchase) {
this.purchase = purchase;
}
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur,
boolean OnMailingList, double Discount, PreferredCustomer preferredCustomer) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
preferredCustomer.discount = discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
}
public class a6main {
public static void main (String [] args) {
public PreferredCustomer() {
}
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821","2000", true, "1000");
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
}
You have several mistakes here. I've corrected them, and the program launches, providing the result:
Name: Al
Address: 222BurdSt
Telephone number: 2102223321
Customer ID: 46821
Amount spent: 2000
On mailing list: true
Discount: 10.0
Remove PreferredCustomer constructor from the main method. It can't be a part of a
method, it is a part of a class. Then, the constructor for PreferredCustomer is already present in PreferredCustomer class.
Hopefully, your customer and PreferredCustomer classes are in separate files? If not, put them in separate files named customer.java and PreferredCustomer.java. In PreferredCustomer class constructor, remove PreferredCustomer preferredCustomer from arguments. It's redundant: why you need to pass one customer into another? Do customers have any relationships with each other? Now the number of arguments will match when you call the constructor (and don't use strings "2000", "1000" where should be integers):
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
2000, true, 1000);
Further in the PreferredCustomer constructor, use this instead of preferredCustomer here: this.discount = Discount; and print Discount with upper case, as in the signature of the constructor.
As a result, the code of the constructor should be:
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur, boolean OnMailingList, double Discount) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
this.discount = Discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
The main method in a6main class:
public static void main (String [] args) {
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821", 2000, true, 1000);
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
And take care of naming conventions, as other people pointed.
Good Morning, I've been given the assignment to:
rewrite the CommissionEmployee class as a subclass of Employee. CommissionEmployee should contain only the instance variables and methods that are not declared in superclass Employee. CommissionEmployee's constructor should invoke Employee's constructor and CommissionEmployee's toString method should invoke Employee's toString method.
Create a Driver class to test your new CommissionEmployee class. Prompt the user to input the first name, last name, social security number, gross sales, and commission rate and create a CommissionEmployee object, using the toString method to print its information.
The issue I seem to be having is class CommissionEmployeeTest will not output what I've placed in my toString method of class CommissionEmployee. I feel like like my superclass Employee is correct as well as me test class but my belief is the error lies somewhere in the method I've created to determine the earnings. The output I'm looking for is
Employees First Name Last Name
Social Security NUmber
Earnings
Earnings would be the total of gross sales + (commission rate * gross sales)
Here is what I have along with the error:
class Employee
public class Employee extends Object {
protected final String firstName;
protected final String lastName;
protected final String socialSecurityNumber;
public Employee(String firstName, String lastName, String socialSecurityNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
#Override
public String toString() {
return String.format(firstName, lastName, socialSecurityNumber);
}
}
class CommissionEmployee
public class CommissionEmployee extends Employee {
private double grossSales;
private double commissionRate;
private double earnings;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales,
double commissionRate, double earnings) {
super(firstName, lastName, socialSecurityNumber);
if (grossSales < 0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
this.grossSales = grossSales;
this.commissionRate = commissionRate;
}
public void setGrossSales(double grossSales) {
if (grossSales < 0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
this.grossSales = grossSales;
}
public double getGrossSales() {
return grossSales;
}
public void setCommissionRate(double commissionRate) {
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
this.commissionRate = commissionRate;
}
public double getCommissionRate() {
return commissionRate;
}
public Double earnings(double d) {
return earnings(grossSales+ (commissionRate * grossSales));
}
public double getEarnings() {
return earnings;
}
public void setEarnings(double earnings) {
this.earnings = earnings;
}
#Override
public String toString() {
return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f%n%s: %.2f%n%s",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"Total earnings", earnings(earnings));
}
public void setFirstName(String firstName) {
}
public void setLastName(String lastName) {
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
}
public void setGrossSales(String grossSales) {
}
public void setCommissionRate(String commissionRate) {
}
}
class CommissionEmployeeTest
//CommissionEmployee test program.
import java.util.Scanner;
public class CommissionEmployeeTest {
public static void main(String[] args) { // instantiate CommissionEmployee object
CommissionEmployee employee =
new CommissionEmployee(null, null, null, 0, .1, 0);
Scanner input = new Scanner(System.in);
// get commission employee data
System.out.printf(
"Employee information obtained by get methods:%n");
System.out.printf("Enter employee's First name:");
String firstName = input.nextLine();
employee.setFirstName(firstName);
System.out.printf("Enter employee's last name:");
String lastName = input.nextLine();
employee.setLastName(lastName);
System.out.printf("Enter employee's social security number:");
String socialSecurityNumber = input.nextLine();
employee.setSocialSecurityNumber(socialSecurityNumber);
System.out.printf("Gross sales for employee:");
String grossSales = input.nextLine();
employee.setGrossSales(grossSales);
System.out.printf("Commission rate for employee:");
String commissionRate = input.nextLine();
employee.setCommissionRate(commissionRate);
System.out.printf("%n%s:%n%n%s%n",
"Updated employee information obtained by toString",
employee.toString());
}
}
Error
Employee information obtained by get methods:
Enter employee's First name:John
Enter employee's last name:Doe
Enter employee's social security number:123456789
Gross sales for employee:4000.00
Commission rate for employee:.1
Exception in thread "main" java.lang.StackOverflowError
at CommissionEmployee.earnings(CommissionEmployee.java:45)
I've tried manipulating my toString method in CommissionEmployee as well as my method to determine earnings but I feel like I'm spinning my wheels. I appreciate any help. I have 1 week left in class and feel like I can contribute more information each week when I post a question then I did the last. Thank you in advance.
I have resolved the issue. After reviewing and revising(several times) I have found my answer. I needed revision on my toString method as well as my earnings method. Cleaned up quite a bit of the code and resolved.
I am trying to create an array list that contains all employees and is able to handle any type of employee. I also have to load the data onto to the list The class I'm using is called payroll. This is what I have so far:
The employee class looks like this:
import java.util.*;
public abstract class Employee
{
private String name, employeeNum, department;
private char type;
public Employee()
{
name ="";
employeeNum = "";
department = "";
}
public Employee(String Name, String EmpNum, String Depart)
{
name = Name;
employeeNum = EmpNum;
department = Depart;
}
//public EMpoy
public String getName()
{
return name;
}
public String getEmployeeNum()
{
return employeeNum;
}
public String getDepartment()
{
return department;
}
public char getType()
{
return type;
}
public void setName(String Name)
{
name = Name;
}
public void setEmployeeNum(String EmpNum)
{
employeeNum = EmpNum;
}
public void setDepartment(String Depart)
{
department = Depart;
}
public String toString()
{
String str;
str = "Employee Name: " + name + "\n"
+ "Employee Number: " + employeeNum + "\n"
+ "Employee Department: " + department + "\n";
return str;
}
}
The payroll class looks like this so far:
import java.util.*;
import java.io.*;
public class Payroll
{
private ArrayList<Employee> list = new ArrayList<Employee>();
private String fileName;
public Payroll()
{
}
public void fileName(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("InsertFileName");
String fileName1 = kb.next();
fileName = fileName1 + ".txt";
}
public void loadData() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNext())
{
String name = s.next();
String employeeNum = s.next();
String department = s.next();
//String typeString = s.next();
//char type = typeString.toUpperCase().charAt(0);
char type = s.next().toUpperCase().charAt(0);
if (type == 'S')
{
double yearlySalary = s.nextDouble();
list.add(new Salary (name, employeeNum, department, yearlySalary));
}
else if (type == 'H')
{
double hourlyPayRate = s.nextDouble();
String hours = s.next();
int hoursWorked = Integer.parseInt(hours);
list.add(new Hourly (name, employeeNum, department, hourlyPayRate, hoursWorked));
}
else if (type == 'C')
{
int numOfWeeks = s.nextInt();
double baseWeeklySalary = s.nextDouble();
int salesThisWeek = s.nextInt();
int salesThisYear = s.nextInt();
double commissionRate = s.nextDouble();
list.add(new Commission (name, employeeNum, department, numOfWeeks, baseWeeklySalary, salesThisWeek, salesThisYear, commissionRate));
}
}
s.close();
}
Now I know I'm supposed to make the arraylist in the constructor, that's what I'm having trouble with. How can I make the list using polymorphism to get every employee? Thanks.
Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared
I am new to OOP and programming in general. I am having trouble with how to put things in the parent class and call them from the other classes and main.
I have the following arraylist creators in main, but feel to be really OOP these should be in the parent and subclasses and just called from main. Is this is correct can someone help me with how this would work.
How do I get the arraylist in the parent class and then call it correctly from main?
This is what I have for main:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
int type = 0;
while(type != 5){
System.out.println("Please select an option:");
System.out.println("Personal Contact: Enter 1");
System.out.println("Business Contact: Enter 2");
System.out.println("Display Personal Contacts: Enter 3");
System.out.println("Display Business Contacts: Enter 4");
System.out.println("5 to quit");
type = input1.nextInt();
if(type == 5){
System.out.println("Goodbye");
break;
}
ArrayList<Contact> contacts = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
Contact pcontact = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
contacts.add(pcontact);
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = input.nextLine();
System.out.println("Please enter Organization: ");
String organization = input.nextLine();
Contact bcontact = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
contacts.add(bcontact);
}
}
}
}
This is what I have for the parent class:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public abstract class Contact {
String contactId;
String firstName;
String lastName;
String address;
String phoneNumber;
String emailAddress;
public Contact(String contactId,String firstName,String lastName, String address, String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){
this.contactId = input;
}
public String getContactId(){
return contactId;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getLastName(){
return lastName;
}
public void setAddress(String input){
this.address = input;
}
public String getAddress(){
return address;
}
public void setPhoneNumber(String input){
this.phoneNumber = input;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setEmailAddress(String input){
this.emailAddress = input;
}
public String getEmailAddress(){
return emailAddress;
}
void displayContacts(){
System.out.println("Contact ID:" + contactId + " First Name:" + firstName + " Last Name:" + lastName);
System.out.println("Address:" + address);
System.out.println("Phone Number:" + phoneNumber);
System.out.println("Email Address:" + emailAddress);
}
}
One of my subclasses: other same just adds a few more variables:
Display Contact(): doesn't work not sure what to do with it either.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ooo1;
public class PersonalContact extends Contact {
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){
this.dateofBirth=input;
}
public String getDateofBirth(){
return this.dateofBirth;
}
#Override
public void displayContacts(){
System.out.print("Personal Contacts: ");
System.out.println("Contact ID:" + contactId + " First Name:" + firstName + " Last Name:" + lastName);
System.out.println("Address:" + address);
System.out.println("Phone Number:" + phoneNumber);
System.out.println("Email Address:" + emailAddress);
System.out.println("Birthday:" + dateofBirth);
}
}
You probably want something like this.
public class AddressBook<T extends Contact>
{
private List<T> contacts = new ArrayList<T>();
public void addContact(T contact)
{
contacts.add(contact);
}
}
You could instantiate and use this class like this.
AddressBook<Contact> book = new AddressBook<Contact>();
book.add(new PersonalContact(...));
book.add(new BusinessContact(...));
Then over time you have the flexibility to add methods to AddressBook that work with the underlying collection. For instance you might want to search for contacts with a particular name. Or return an iterator of Contacts ordered by a particular attribute.
You can add a method in class Contact :
public void getData(){
// take in all the inputs here, so that you can directly store them in class member variables instead of passing them from main.
}
Assuming that PersonalContact & BusinessContact are inherited classes from Contact.
You can add a method in them:
class PersonalContact extends Contact{
String dateofBirth;
public void getData(){
super.getData(); //calls getData() method from base class
// take DOB as input & store it
}
similarly for BusinessContact class.
I suggest you take a look at abstract classes & interfaces for future use.
The Contact class seems okay. But ContactList not that much. It's supposed to be a data structure for contacts, so there's not reason for main method there.
public class ContactList {
private ArrayList<Contact> contacts;
public ContactList(){
this.contacts = new ArrayList<Contact>();
}
public void addContact(Contact contact){
this.contacts.add(contact);
}
public Contact getContact(int index){
return contacts.get(index);
}
// other methods that work with the data structure
// f.e. searching, deleting, ...
}
and then you could have some ContactUtil class that would take care of reading contact info from user (what you had in you main method).
public final class ContactUtil {
private ContactUtil(){} // we don't want to create instances of this class
public static Contact readNewContact(){
Scanner input1 = new Scanner(System.in);
int type = 0;
...
return contact;
}
}
And finally you will have some class just for main():
public class Main {
public static void main(String[] args){
ContactList myContacs = new ContactList();
myContacts.add(ContactUtil.readNewContact());
Contact contact = ContactUtil.readNewContact();
myContacts.add(contact);
}
}