Java retrieve data from attribute classes - java

I am new to objects and classes in java. I want to know how to get data from attribute objects. I have 4 classes
public class Personnel {
private ArrayList<Employee> employees = new ArrayList<Employee>();
public void addEmployee(Employee employee){
employees.add(employee);
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
public class Employee{
/**DATAFIELDS*/
private String name;
Address address;
PayInfo pay;
//Constructor
//methods
.....
}
public class PayInfo {
/**DATAFIELDS*/
private double salary;
private boolean isFullTime;
//Constructors
//Methods
....
}
public class Address {
/**DATAFIELDS*/
private String streetAddress;
private String city;
private String state;
private String zipCode;
//Constructors
//Methods
.....
}
I have created payInfo and address objects and added to the employee object. And finally added that employee object to the Personnel object and saved in an ArrayList. But my question is, whether is there any way to retrieve all these information from just Personnel object rather than going through each objects ? Thanks in advance !!
I mean i want something like this from my Main method,
public static void main(String[] args) {
//Create CODPersonnel Object
CODPersonnel personnelEmployee = new CODPersonnel();
//Address Object for emp1 Object
Address addressEmp1 = new Address();
addressEmp1.setStreetAddress("637 67th Place");
addressEmp1.setCity("Willowbrook");
addressEmp1.setState("IL");
addressEmp1.setZipCode("60527");
//PayInfo for emp1 object
PayInfo emp1PayInfo = new PayInfo();
emp1PayInfo.setFullTime(true);
emp1PayInfo.setSalary(85000.0);
//Create the Employee object
//and set attributes
Employee emp1 = new Employee();
emp1.setName("Samantha Simmons");
emp1.setAddress(addressEmp1);
emp1.setPay(emp1PayInfo);
//Add objects to CODPersonnel objects
personnelEmployee.addEmployee(emp1);
}
And i want to retrieve all information through Personnel object like,
System.out.println(personnelEmployee.getEmployees(......);
or,
System.out.println(personnelEmployee.getAddress.streetName..etc,) something like that. I know it may sound stupid but is there any way like that??

You could put PayInfo and Address into a Details class. Each Employee could be composed of a Details object. You can then access the Details object from the Personnel class:
class Personnel {
private Map<String, Employee> employees = new HashMap<>();
public void addEmployee(Employee employee) {
employees.put(employee.getName(), employee);
}
public Details getEmployeeDetails(String name) {
return employees.get(name).getDetails();
}
}
class Employee {
private String name; //could be stored in Details
private Details details;
public Employee(String name, Details details) {
this.details = details;
}
public Details getDetails() {
return details;
}
public String getName() {
return name;
}
}
class Details {
private PayInfo payInfo;
private Address address;
public Details(PayInfo payInfo, Address address) {
this.payInfo = payInfo;
this.address = address;
}
public PayInfo getPayInfo() {
return payInfo;
}
public Address getAddress() {
return address;
}
}
I switched your List into a Map, so you can easily access each employee by name. You could then do:
public static void main(String[] args) {
PayInfo info = ...;
Address address = ...;
Details details = new Details(info, address);
String name = ...
Employee employee = new Employee(name, details);
Personnel personnel = new Personnel();
personnel.addEmployee(employee);
//example
Details employeeDetails = personnel.getEmployeeDetails("Some Name");
Address employeeAddress = employeeDetails.getAddress();
System.out.println(employeeAddress.getStreetAddress());
}
This design strongly violates the Law of Demeter, so if you're looking for a design that doesn't violate it, I'll be more than happy to edit in a stronger design.

Not sure what you're asking. You can access the information from the Employee objects in the ArrayList in Personnel, assuming you have the appropriate getters and setters in Employee that returns its PayInfo and Address.

Related

java: ensure that there is only one instance of the type

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.
}

Add new class variable java + getter/setter method without editing class

Is there any way to create new class variable or method in java without editing class java
Example:
I have class Person
public class Person {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
and in main class I process like this:
Person personData = new Person();
personData.setName("My Name");
personData.setAddress("Address");
List<Person> person = new ArrayList<Person>();
person.add(personData);
I want to add new person variable in List
and have setNo(); and getNo();
So list index[0] have person with property No, Name, And Address without editing the class Person first.
There is no way in Java to add methods to a class without changing the class source code.
The only possibility you have is to either extend from this class (by creating a subclass that inherits from Person) or to create a completely new class that contains a Person object.
The first concept is called inheritance; the second one composition. You can find a discussion of "one versus the other" here for example.
But in essence the answer: step back and read a good book about Java.
I would probably create another class which extends Person.
import java.util.ArrayList;
import java.util.List;
public class PersonNo extends Person {
public static void main(String[] args) {
PersonNo personData = new PersonNo();
personData.setName("My Name");
personData.setAddress("Address");
List<PersonNo> person = new ArrayList<>();
person.add(personData);
}
public void setNo(int n) {
this.no = n;
}
public int getNo() {
return this.no;
}
private int no;
}
This requires you to change the List type to "PersonNo" and to add "PersonNo"s, but it will give you the functionality you need. If you create the List with "Person", you can add "PersonNo"s but you will not have the setNo/getNo unless you cast the "Person" into a (PersonNo).

Employee Management System in Java

I am new to Java and working in Employee management system . I have created few classes including Employee(name, dob etc), Department (dept name, description etc). I have a requirement that Department must have 2 empoyee and less than 10.
Can anyone tell me how to make that association?
Department class:
public class Department {
private String departmentName;
private String locationofDep;
Employee emp = new Employee()
Getter.. setter
}
public class Employee {
private String empName;
private String dob;
Getter.. setter
}
According to the question you should have a collection of Employee object. So you have to create Employee Collection such List, Set and etc. However you cannot limit the capacity a Collection such between two values. Programmatically only thing you can do is throw an Exception when calling the getter method of the Collection. You can put two default value to the Collection. I don't believe that would work for you. Do following modifications in your code.
public class Department {
private String departmentName;
private String locationofDep;
//collection of empleyees
Set<Employee> employees = new HashSet<>();
//use this method to add employees
public void addEmployee(Employee employee) {
this.employees.add(employee);;
}
public Set<Employee> getEmployees() throws Exception {
if (this.employees.size() < 2 || this.employees.size() > 10) {
throw new Exception("Employees out of capacity");
}
return this.employees;
}
//other getters and setters should be here
}
public class Employee {
private String empName;
private String dob;
//put getters and setters
}
So you can manage the employee length problem when you getting employee information using try-catch blocks

java - Editing child in list of parents

I've got an abstract class called customer and another classe called payCust that extends this abstract class. There is another client class that initializes a list of customers.List<Customer> custList = new ArrayList<>();
the customer class has a constructor as follows:
public Customer(String name, String email, String mag) {
this.CusEmail = email;
this.CusName = name;
this.magazine = mag;
}
payCust has the following constructor:
public PayCust(String _name, String _email, String _accountType, String _custMag) {
super(_name, _email, _custMag);
this.accountType = _accountType;
}
all the variables have public get and set methods. e.g.
public void setName(String name) {
this.CusName = name;
}
public String getName() {
return this.CusName;
}
my question is that if the custList had a PayCust added to it. how can i edit the accountType of a customer from that list?
note: email is unique to every customer
You will have to check the instance type of the object within the ArrayList and cast it for usage.
Something like this, for example:
for (Customer c : custList){
if(c instanceof PayCust){
PayCust pc = (PayCust) c;
pc.getAccountType();
}
}
You would have to cast it to a PayCust (assuming you know for a fact that it's a PayCust):
PayCust example = (PayCust) custList.get(0);
String accountType = example.getAccountType ();
...

How do I use Java getters and setters with a collection of data without explicitly typing out the attributes for each item?

I am very new to Java and to programming in general, and I have an assessment to complete where I load employees (with name, age, and department attributes; department can be only one of four enumerated values) into a program that will sort them by age and tell if the age is a prime number. The assignment requires Company, Department, and Employee classes. I am confident that I can figure out age/prime components — I know how to google for algorithms. What I am struggling with is putting all the discrete pieces into a cohesive whole.
Here is what I have so far. I've put in one employee, but the way I'm doing it seems completely inelegant and inefficient. I am sure there is a better way, but I've hit a mental block.
EDIT: as was pointed out below, I was unclear. What I am asking help with is populating the data structure.
Company class:
public class Company {
static Employee one = new Employee();
public static void main(String[] args) {
one.setName("Counting Guru");
one.setAge(55);
one.setDepartment(DepartmentList.ACCOUNTING);
}
}
DepartmentList class:
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
public enum DepartmentList {
ACCOUNTING, MARKETING, HUMANRESOURCES, INFORMATIONSYSTEMS;
public static void main(String[] args) {
Map<DepartmentList,String>
enumMap=new EnumMap<DepartmentList,String>(DepartmentList.class);
enumMap.put(DepartmentList.ACCOUNTING, "Accounting");
enumMap.put(DepartmentList.MARKETING, "Marketing");
enumMap.put(DepartmentList.HUMANRESOURCES, "Human Resources");
enumMap.put(DepartmentList.INFORMATIONSYSTEMS, "Information Systems");
Set<DepartmentList> keySet = enumMap.keySet();
for (DepartmentList department : keySet) {
String value = enumMap.get(department);
System.out.println("ENUMMAP VALUE:"+value);
}
}
}
Employee class:
public class Employee {
String empName;
int empAge;
DepartmentList empDept;
Employee() {
}
public String getName() {
return empName;
}
public void setName(String name) {
this.empName = name;
}
public int getAge() {
return empAge;
}
public void setAge(int age) {
this.empAge = age;
}
public DepartmentList getDepartment() {
return empDept;
}
public void setDepartment(DepartmentList department) {
this.empDept = department;
}
public Employee(String empName, int empAge, DepartmentList empDept){
}
}
I also have a Department class, but it's currently empty.
Am I on the right track? Can someone give me a nudge? Thank you!
Don't hard-code the data inside the Java program. Put the data in a file and write methods to load the data.
If you MUST hardcode the data in the program, use something like this sample:
public class Employee
{
String name;
int age;
public Employee(String name, int age)
{
this.name = name;
this.age = age;
}
// getters, setters, etc.
}
In the main program
private static Employee[] empData =
{
new Employee("John Smith", 50),
new Employee("Fred Jones", 25),
.
.
.
};
Now you have a static array of Employee objects that you can "load" into your data structure.
If you're asking if there is something like a property in Java, no, there isn't (at least not yet).
If you're asking how to populate your objects something like an IOC container, like Spring, would be a better choice.
Now as it comes to your code you have two main methods in two different classes. Only one will be called. If you want to create a static instance you will be better do
static Employee one = new Employee("Counting Guru", 55, DepartmentList.ACCOUNTING);
or
static Employee one = new Employee();
static {
one.setName("Counting Guru");
one.setAge(55);
one.setDepartment(DepartmentList.ACCOUNTING);
}
When it comes to the enum then you'll better define a constructor for it
public enum DepartmentList {
ACCOUNTING("Accounting"), MARKETING("Marketing");
private String displayName;
public DepartmentList(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return diplayName;
}
}
In the Employee constructor you need to assign the field values to the ones received as arguments.

Categories