I have 2 different classes, Employee, PersonnelManager. I am trying to declare and instantiate an array of Employee in PersonnelManager. without using inheritance, just two completely seperate classes
public abstract class Employee {
private String firstName;
private String lastName;
private double wage;
public Employee() {
firstName = "";
lastName = "";
wage = 0.0;
}
}
public class PersonnelManager {
public Employee [] EmployeesArray;
public PersonnelManager() {
EmployeesArray= {Employee.this()}; // this is not working
}
in the Constructor of PersonnelManager How can I instantiate the array. Thank you.
You can initialize the array like below -
public PersonnelManager() {
EmployeesArray= new EmployeesArray[5];
}
or you can pass the size in constructor to make it dynamic-
public PersonnelManager(int size) {
EmployeesArray= new EmployeesArray[size];
}
Hope this will help you.
public abstract class Employee {
private String firstName;
private String lastName;
private double wage;
public Employee() {
firstName = "";
lastName = "";
wage = 0.0;
}
}
public class PersonnelManager {
public Employee [] EmployeesArray;
public PersonnelManager() {
EmployeesArray= new Employee[10]; // 10 is the size of an array
}
I think you're trying to instantiate an empty array of Employees in your PersonnelManager, but you're using the wrong syntax. You can do that with this:
EmployeesArray = new EmployeesArray[size];
Note that you'll have to supply a size. If you want more flexibility, then you might want to use a List instead of an array:
public class PersonnelManager {
public List<Employee> employees;
public PersonnelManager() {
employees = new ArrayList<>();
}
}
Related
I am following the example from:
https://www.baeldung.com/java-composite-pattern
public class FinancialDepartment implements Department {
private Integer id;
private String name;
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
}
// standard constructor, getters, setters
}
public class SalesDepartment implements Department {
private Integer id;
private String name;
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
}
// standard constructor, getters, setters
}
public class HeadDepartment implements Department {
private Integer id;
private String name;
private List<Department> childDepartments;
public HeadDepartment(Integer id, String name) {
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<>();
}
public void printDepartmentName() {
childDepartments.forEach(Department::printDepartmentName);
}
public void addDepartment(Department department) {
childDepartments.add(department);
}
public void removeDepartment(Department department) {
childDepartments.remove(department);
}
}
I want to prevent my self from able to add two of the same types to HeadDepartment
for example if it call add addDepartment twice for the same type, there should be only one
public class CompositeDemo {
public static void main(String args[]) {
Department salesDepartment = new SalesDepartment(
1, "Sales department");
Department salesDepartment2 = new SalesDepartment(
1, "Sales department");
Department salesDepartment3 = new SalesDepartment(
3, "Sales department");
Department financialDepartment = new FinancialDepartment(
2, "Financial department");
HeadDepartment headDepartment = new HeadDepartment(
3, "Head department");
headDepartment.addDepartment(salesDepartment);
headDepartment.addDepartment(financialDepartment);
// only keep the latest of same instanceof ie replace
headDepartment.addDepartment(salesDepartment2);
headDepartment.addDepartment(salesDepartment3);
// this should only print twice one for salesDepartment3 and financialDepartment
headDepartment.printDepartmentName();
}
}
i suppose do i just iterate the list and if instanceof, replace and put?
public void addDepartment(Department department) {
childDepartments.add(department);
}
i would like to keep the order as well if the instnaceof Department was the first, i would like it to keep it as 1st, meaning it should print salesDepartment3 before financialDepartment
Your addDepartment() needs to iterate over the list of children and compare each one's class to the class of the object you are adding.
Pseudo code:
Class addClass = itemToAdd.getClass();
for each child
{
if (child.getClass() == addClass)
{
//class is already in the list so replace it.
}
Hello i can not write the JTextField's value to the ArrayList in another class the error is "...String can not be converted to Object" how can i fix it?
here is the arraylist class
public class MemberList
{
private ArrayList < Member> members;
/**
* Create a Member.
*/
public MemberList()
{
members = new ArrayList < Member>();
}
/**
* Add a member to this member list.
* #param member the member to be added
*/
public void addMember(Member member)
{
members.add(member);
}
}
and the GUI
public class Test extends JFrame implements ActionListener {
private JTextField jtFName, jtLName, jtMemberNo;
private int nextMemNo;
private MemberList members;
private JFrame frame;
#Override
public void actionPerformed(ActionEvent evt) {
members = new MemberList();
if (evt.getActionCommand().equals("Add Member")) {
if (jtLName.getText().equals("") && (jtFName.getText().equals(""))) {
jtMember.setText("No names");
} else if (jtFName.getText().equals("")) {
jtMember.setText("No first name");
} else if (jtLName.getText().equals("")) {
jtMember.setText("No last name");
} else if (!jtLName.getText().equals("") && (!jtFName.getText().equals(""))) {
btnOne.setText("Confirm");
String fName = jtFName.getText();
String memNo = "1";
String lName = jtLName.getText();
members.addMember(member);
}
} else if (evt.getActionCommand().equals("No. of Members")) {
btnTwo.setText("Clear Number");
jlbMember.setVisible(true);
} else if (evt.getActionCommand().equals("Clear Number")) {
jtFName.setText("");
jtLName.setText("");
} else if (evt.getActionCommand().equals("Quit")) {
System.exit(0);
}
}
}
What do i need to do to add jtFName in the ArrayList?
Sorry for the bad editing and thanks
You have to create a new instance of your Member class and pass it to your addMember method. For example
Member member = new Member(fName, lName); //replace with your actual constructor logic
members.addMember(member);
Your List members contains object of type Member not of type String
Either you make that your List contains String like:
members = new ArrayList<String>();
Or you make a constructor for your Member class in which you pas the String to the object and add the new Object to the List like:
public class Member{
private String name;
public Member(String name){ //create constructor with String argument
this.name = name;
}
}
members.addMember(new Member(name)) //add new Member to list
I can't see your Member class but when I look at your code I think it has a fName, lName and memNo. So in your program the constructor will look like:
public class Member{
private String fName;
private String lName;
private String memNo;
public Member(String fNamen, String lName, String memNo){ //create constructor with String arguments
this.fName= fName;
this.lName= lName;
this.memNo= memNo;
}
}
And add it to the List like:
members.addMember(new Member(fName, lName, memNo));
I am not too familiar with enum classes in java. And was wondering if this is an appropriate way to do the following.. (or if there is a better way of doing this)
Essentially what I am trying to do is I have a list of Employees and I'd like to associate with it specific subclasses of parent classes.
public enum Employees {
BOB (new Level2Salary(salaryPlan), new SystemsDept())
MARY (new Level3Salary(salaryPlan), new SoftwareDept()),
SUSAN (new Level2Salary(salaryPlan), new SystemsDept()),
PETER (new BaseSalary(salaryPlan), new TestDept());
private Salary salary;
private Dept dept;
Employees(Salary salary, Dept dept){
this.salary = salary;
this.dept = dept;
}
public Salary getSalary() {
return salary;
}
public Salary getDept() {
return dept;
}
}
public class Level2Salary extends Salary {
private SalaryPlan salaryPlan;
public Level2Salary(SalaryPlan salaryPlan) {
this.salaryPLan = salaryPlan;
}
}
public class SystemsDept extends Dept {
public SystemsDept(){}
}
}
I want to be able to do this so when I call Employees.BOB.getSalary() it will return the appropriate instantiated subclass that is associated with this enum value. (i.e. Level2Salary subclass)
If anyone has better suggestions of this besides using enums, feel free to suggest. Thanks
That cannot be done with an enum. However, you can make a non-enum class which acts just like an enum: Create a class which only has private constructors, but which has public static final fields whose types are the class itself. Many classes introduced before Java 5 are examples of this, such as:
TextAttribute
DateFormat.Field
JobState
FileChannel.MapMode
The newer StandardSocketOptions not only follows the above pattern, but also uses generics to do exactly what you want: It allows the NetworkChannel.getOption method to return a different subtype for each constant.
In your case, you would replace your enum type with a class designed like StandardSocketOptions:
public class Employees<S extends Salary, D extends Dept> {
public static final Employees<Level2Salary, SystemsDept> BOB =
new Employees<>(new Level2Salary(salaryPlan), new SystemsDept());
public static final Employees<Level3Salary, SoftwareDept> MARY =
new Employees<>(new Level3Salary(salaryPlan), new SoftwareDept());
public static final Employees<Level2Salary, SystemsDept> SUSAN =
new Employees<>(new Level2Salary(salaryPlan), new SystemsDept());
public static final Employees<BaseSalary, TestDept> PETER =
new Employees<>(new BaseSalary(salaryPlan), new TestDept());
private final S salary;
private final D dept;
private Employees(S salary, D dept){
this.salary = salary;
this.dept = dept;
}
public S getSalary() {
return salary;
}
public D getDept() {
return dept;
}
}
friends and colleagues. I have following class:
public class Department {
private String departmentName;
private int moneyForDepartment;
public Department(String departmentName, int moneyForDepartment){
if (moneyForDepartment < 0){
throw new IllegalArgumentException("invalid value");
}
this.departmentName = departmentName;
this.moneyForDepartment = moneyForDepartment;
}
public Department(){
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public int getMoneyForDepartment() {
return moneyForDepartment;
}
public void setMoneyForDepartment(int moneyForDepartment) {
this.moneyForDepartment = moneyForDepartment;
}
}
and for example i will create two objects of this class:
Department dep1 = new Department("Storage", 100000);
Department dep2 = new Department("Storage", 200000);
Please tell me how can i forbid to create class object in case when object of this class with the same first parameter is already exists ?
It's probably not a good idea to do that globally across your entire application (in static state), because then testing becomes difficult. Instead, create a factory for your Department class, maybe looking something like this:
public class Department {
private Department(String departmentName, int moneyForDepartment) { ... }
...
public static class Factory {
private Set<String> seenDepartmentNames = new HashSet<>();
public Department create(String departmentName, int moneyForDepartment) {
if (!seenDepartmentNames.add(departmentName)) {
throw new IllegalArgumentException("Department already created");
}
return new Department(departmentName, moneyForDepartment);
}
}
}
This forces all construction to go through the Factory, since the Department constructor is private. Just use one Factory across your application, and you can still create new ones for testing without running into problems.
You could create a static field in the Department class and keep a Set with the department names already used:
public class Department {
private static final Set<String> usedDepartmentNames = new HashSet<>();
...
}
Then, in the constructor, do:
public Department(String departmentName, int moneyForDepartment) {
if (usedDepartmentNames.contains(departmentName)) {
throw new IllegalArgumentException("Department already exists");
}
if (moneyForDepartment < 0){
throw new IllegalArgumentException("invalid value");
}
this.departmentName = departmentName;
this.moneyForDepartment = moneyForDepartment;
usedDepartmentNames.add(departmentName);
}
I am trying to print the first element on the two arrays in my Athlete class, country and name. I also need to create a object that simulates three dive attemps an athlete had (that is initially set to zero). I am new to OOP and I dont know how to go abouts doing this in my main... as far as constructors go. This is what i have done so far...
this is the main:
import java.util.Random;
import java.util.List;
public class Assignment1 {
public static void main(String[] args) {
Athlete art = new Athlete(name[0], country[0], performance[0]);
}
}
I just really am not sure what to do...
And this is the class with the arrays.
import java.util.Random;
import java.util.List;
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
//Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.)
Athlete(String[] name, String[] country, Performance[] performance) {
this.name = name;
this.country=country;
this.performance=performance;
}
public Performance Perform(Dive dive){
dive.getDiveName();
return null;
}
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String[] getCountry() {
return country;
}
public void setCountry(String[] country) {
this.country = country;
}
}
thanks in advance for any help and input!
btw there is other classes too, just not relevant atm..
First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.
However, if you really want to use that Getter and Setter, change the public modifier to private instead.
Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");
Variable name will be equal to "theolc".
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
Your attempt at an athlete class seems to be dealing with a group of athletes, which is a design fault.
Define a class to represent a single athlete, with fields that represent the athlete's attributes:
public class Athlete {
private final String name;
private final String country;
private List<Performance> performances = new ArrayList<Performance>();
// other fields as required
public Athlete (String name, String country) {
this.name = name;
this.country = country;
}
// getters omitted
public List<Performance> getPerformances() {
return performances;
}
public Performance perform(Dive dive) {
// not sure what your intention is here, but something like this:
Performance p = new Performance(dive, this);
// add new performance to list
performances.add(p);
return p;
}
}
Then your main method would use ti like this:
public class Assignment1 {
public static void main(String[] args) {
String[] name = {"Art", "Dan", "Jen"};
String[] country = {"Canada", "Germant", "USA"};
Dive[] dive = new Dive[]{new Dive("somersault"), new Dive("foo"), new Dive("bar")};
for (int i = 0; i < name.length; i++) {
Athlete athlete = new Athlete(name[i], country[i]);
Performance performance = athlete.perform(dive[i]);
// do something with athlete and/or performance
}
}
}
I think you are a little messed up with what you doing.
Athlete is an object, athlete has a name, i has a city where he lives.
Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
public static void main(String[] args) {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
// initialize your performance array here too.
//Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
Athlete art = new Athlete(name, country, performance);
}
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
#Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.