Я изучаю объектно-ориентированное программирование в курсе Java, и я делаю проект, в котором программа создает три типа объектов: адрес, дата и Наемный рабочий. Программа хранит данные нескольких сотрудников, а затем отображает данные в массиве типа Employee.Создание статической ссылки на нестатический метод в другом классе
Я использую четыре различных класса: Address
класс, Date
класса, и Employee
класса, и EmployeeTest
класса, который создает массив.
Вот Адрес класс:
public class Address {
private String Street;
private String City;
private String State;
private int ZipCode;
public Address(String St, String Ci, String Sta, int Zip){
Street = St;
City = Ci;
State = Sta;
ZipCode = Zip;
}
public String getEmployeeAddress(){
return (Street + ", " + City + ", " + State + " " + ZipCode);
}
}
Датой Класс:
public class Date {
private int Month;
private int Day;
private int Year;
public Date(int M, int D, int Y){
Month = M;
Day = D;
Year = Y;
}
public String getDateString(){
return (Month + "/" + Day + "/" + Year);
}
}
И Сотрудник Класс:
public class Employee {
private int EmployeeNum;
public void setEmployeeNum(int ENum){
EmployeeNum = ENum;
}
public int getNum(){
return EmployeeNum;
}
public String getDate(){
return Date.getDateString();
}
public String getName(){
return Name.getEmployeeName();
}
public String getAddress(){
return Address.getEmployeeAddress();
}
}
Все эти классы в одном пакете (Я использую Eclipse). Точка класса Employee - создать объект типа Employee и получить его адрес, имя и HireDate с помощью классов Address, Name и Date.
место, где массив входит в игру здесь:
import java.util.Scanner;
import java.lang.*;
public class EmployeeTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many employees will have their data stored today?");
int EmployeeAmount = Integer.parseInt(input.nextLine());
Employee [] EmployeeArray = new Employee[EmployeeAmount];
for (int i = 0; i < EmployeeArray.length; i ++){
System.out.print("What is employee " + (i+1) + "'s employee number?");
int EmployeeNumber = Integer.parseInt(input.nextLine());
EmployeeArray[i] = new Employee();
EmployeeArray[i].setEmployeeNum(EmployeeNumber);
System.out.println("What is the first name of employee " + EmployeeNumber + "?");
String EmployeeFirstName = input.nextLine();
System.out.println("What is the last name of employee " + EmployeeNumber + "?");
String EmployeeLastName = input.nextLine();
Name EmployeeName = new Name(EmployeeFirstName, EmployeeLastName);
System.out.println("Please enter the street address: ");
String StreetAddress = input.nextLine();
System.out.println("Please enter the name of the city: ");
String CityName = input.nextLine();
System.out.println("Please enter the two character code for the state: ");
String StateID = input.nextLine();
System.out.println("Please enter this address's zip code: ");
int ZipCode = Integer.parseInt(input.nextLine());
Address EmployeeAddress = new Address(StreetAddress, CityName, StateID, ZipCode);
System.out.println("Finally, what was the month(#) of the hire date?");
int Month = Integer.parseInt(input.nextLine());
System.out.println("What was the day(#)?");
int Day = Integer.parseInt(input.nextLine());
System.out.println("What was the year?");
int Year = Integer.parseInt(input.nextLine());
Date HireDate = new Date(Month, Day, Year);
}
for (int j = 0; j < EmployeeArray.length; j ++){
System.out.println("Employee number: " + EmployeeArray[j].getNum());
System.out.println("Employee Name: " + EmployeeArray[j].getName());
System.out.println("Employee Address: " + EmployeeArray[j].getAddress());
System.out.println("Employee Hiredate: " + EmployeeArray[j].getDate());
}
}
}
Программа запрашивает у пользователя числа сотрудников, которые будут сохранены в массиве, а затем создает Employee[]
размера EmployeeAmount
. Идея кода заключается в том, что для каждого сотрудника в массиве получаются все переменные в других классах: номер сотрудника, имя сотрудника (первый и последний), адрес (уличный адрес, город, государственный код, почтовый индекс), Дата аренды (месяц, день, год). После того, как все это получится, второй цикл for
выполняет итерацию через каждого сотрудника и отображает информацию.
Проблема, которую я имею, что в Employee
классе, Eclipse дает мне ошибку в getDate()
, getName()
и getAddress()
методов. Когда я говорю, например, return Date.getDateString()
, Eclipse говорит, что я не могу статически ссылаться на нестатический метод. Это решение состоит в том, чтобы ставить getDateString()
, и я пробовал это, но проблема в том, что, создавая все методы и переменные в классах Address, Employee и Date, значения блокируются. Это означает, что одни и те же данные будут отображаться для всех сотрудников.
Вот что я имею в виду. Ниже приведен пример вывода, если я сделал все методы и переменные статическими. Текст между звездочками - это то, что вводит пользователь.
How many employees will have their data stored today?**2** What is employee 1's employee number?**1** What is the first name of employee 1? **Bob** What is the last name of employee 1? **Jones** Please enter the street address: **300 1st Avenue** Please enter the name of the city: **New York** Please enter the two character code for the state: **NY** Please enter this address's zip code: **10001** Finally, what was the month(#) of the hire date? **1** What was the day(#)? **1** What was the year? **2001** What is employee 2's employee number?**2** What is the first name of employee 2? **Bobby** What is the last name of employee 2? **Robinson** Please enter the street address: **301 1st Avenue** Please enter the name of the city: **Los Angeles** Please enter the two character code for the state: **CA** Please enter this address's zip code: **90001** Finally, what was the month(#) of the hire date? **1** What was the day(#)? **2** What was the year? **2004** Employee number: 2 Employee Name: Bobby Robinson Employee Address: 301 1st Avenue, Los Angeles, CA 90001 Employee Hiredate: 1/2/2004 Employee number: 2 Employee Name: Bobby Robinson Employee Address: 301 1st Avenue, Los Angeles, CA 90001 Employee Hiredate: 1/2/2004
Делая все переменные и статические методы, значения заблокированы, как показано на рисунке, что делает программу бесполезной. У кого-нибудь есть решение этой проблемы? Мне нужен способ отображения информации каждого сотрудника, ссылаясь на методы в других классах. Теперь, как правило, я бы просто создал все переменные и методы под одним классом под названием Employee
, но в инструкциях назначения указано, что мне нужно создавать отдельные классы.
У сотрудника должен быть экземпляр «Дата» и «Адрес» (и, предположительно, «Имя») его собственного – MadProgrammer
. Должны ли эти экземпляры быть такими же, как и пользовательские входы? – LightFlicker
Не делайте все свои методы статическими или вашими переменными. Удалите статику, создайте экземпляр ваших классов и вызовите методы в экземплярах. – pczeus