Accessing particular, the same instance of an object from different java classes - java

I have 4 different classes: Main, Employee, Company and HRDepartment
Class Company stores employees, new instances of Employees are created in this class
John Doe instance was created in Company class
How to access this particular instance in other classes to change its fields/invoke methods
Please find code below. Thank you.
public class Main
{
public static void main(String[] args)
{
HRDepartment hr = new HRDepartment();
hr.payRenumeration(5000);
// how to print cash of John Doe? I can't type System.out.println(john_doe.getCash())
// because this instance was created in another class
}
}
public class Employee
{
private double cash;
public void addCash(double cash)
{
this.cash += cash;
}
public double getCash()
{
return cash;
}
}
public class Company
{
// New employee is created in Company system
Employee john_doe = new Employee();
}
public class HRDepartment
{
public void payRenumeration(double renumerationToPay)
{
// how to access instance john_doe created in Company class?
// if this was in the same class I could type simply john_doe.addCash(renumerationToPay);
}
}

Related

Java Problem: Calculations in one subclass' constructor affecting fields of another subclass' instance

I have two abstract classes i.e. Medicine and Prescription. All code can be found at https://codeshare.io/aVAdr3 These two classes have subclasses, the class hierarchy diagram is as follows:
and...
The medicine java file:
abstract class Medicine {
public String name;
public int price;
public Medicine (String name, int price) {
this.name = name;
this.price = price;
}
public int getPrice () {
return price;
}
public void setPrice (int newPrice){
price = newPrice;
}
}
class commonDrug extends Medicine {
public commonDrug (String name, int price) {
super(name, price);
}
}
The Prescription java file:
abstract class Prescription {
protected Medicine med;
public Prescription(Medicine med) {
this.med = med;
}
}
class bluePrescription extends Prescription {
public bluePrescription (Medicine med) {
super(med);
System.out.println(med.getPrice()+ "<-- Price for bluePrescription, it should be 30, but the calculations in pPrescriptions affect it.");
}
}
class whitePrescription extends Prescription {
public whitePrescription (Medicine med) {
super(med);
}
}
class pPrescription extends whitePrescription {
public pPrescription (Medicine med) {
super(med);
System.out.println(med.getPrice()+ "<-- Price before calculation for pPrescription");
//Calculations
int priceWithDiscount;
if (med.getPrice()<=20) {priceWithDiscount=0;}
else {priceWithDiscount= med.getPrice()-20;}
med.setPrice(priceWithDiscount);
System.out.println(med.getPrice()+ "<-- Price after calculation for pPrescription");
}
}
The test program is as follows:
class TestProgram {
public static void main (String[] args) {
//Medicine object
commonDrug drug1 = new commonDrug("Paracetamol", 30);
//Prescription objects:
pPrescription prescription1 = new pPrescription(drug1);
bluePrescription prescription2 = new bluePrescription(drug1);
}
}
And when you run the test program you get this in the terminal:
30<-- Price before calculation for pPrescription
10<-- Price after calculation for pPrescription
10<-- Price for bluePrescription, it should be 30, but the calculations in pPrescriptions affect it.
I've been trying to solve this for hours, I can't figure out how I can perform calculations in the pPrescription constructor without affecting instances of bluePrescription. Why is this happening? pPrescription is a subclass of whitePrescriptions, not bluePrescriptions. Anyhow, to instances of a class are completely separate, getPrice and setPrice are not static, so why is using them affecting all the instances of Medicine?
why is using them affecting all the instances of Medicine?
There is only once instance of Medicine in your code.
You pass the same object, i.e. drug1 to both pPrescription and bluePrescription class constructors.
As there's only one object (drug1) that is passed to both classes, if any class modifies it, changes will be reflected everywhere you refer to that object.
One way to fix the problem is to not save the discounted price and just calculate it whenever you need it using a method in the pPrescription class.
class pPrescription extends whitePrescription {
...
public int getDiscountedPrice() {
return med.getPrice() <= 20 ? 0 : med.getPrice() - 20;
}
}
Side note: Class names should begin with a capital letter.

Inherited parent class values are not reflected in JPA save entity

I have a class Vehicle and Car
Vehicle extends Car
Lets take an example
Class Vehicle {
String vehicleMade;
boolean fourWheeler;
Vehicle(String vehicleMade, boolean fourWheeler) {
this.vehicleMade=vehicleMade;
this.fourWheeler=fourWheeler;
}
// getters and setters
}
Class Car extends Vehicle {
String model;
Car(String vehicleMade, boolean fourWheeler) {
super(vehicleMade, fourWheeler);
}
// getters and setters
}
Class JavaMainClass {
private static CarInfoRepository carInfoRepo;
private static AnnotationConfigApplicationContext ctx;
public static void main(String args[]) {
carInfoRepo= ctx.getBean(CarInfoRepository.class);
//Now where I have doubt and problem
Car carInfo = new Car("Bentley", true);
carinfo.setModel("Flying Spur");
log.debug(carInfo.getVehicleMade); // I get Bentley here
carInfoRepo.save(carInfo);
}
}
Now when I get the car object from the repo, I get vehicleMade and fourWheeler attribute as null
You can see when I get that vehicleMade before saving but after saving to the repo I am getting null as the attribute.

Need to code Manager and Employee classes. How do I make them "visible" to each other without breaking encapsulation?

The Manager and the Employee classes are both subclasses of EnterpriseMember. How do I write a "getManager" method (that returns the Manager instance that has this Employee in their List of reports) for the Employee class?
Thanks in advance!
public class Manager extends EnterpriseMember {
/*Fields */
private List reports = new ArrayList();
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public void addReport(Employee employee){
reports.add(employee);
}// How can "employee" know it is in this List?
}
public class Employee extends EnterpriseMember {
/*Constructor */
public Manager(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return ???;
}
}
Something like this:
public class Manager {
private List<Employee> reports = new ArrayList<Employee>();
public void addReport(Employee e) {
if (e != null) {
this.reports.add(e);
e.setManager(this);
}
}
}
public class Employee {
private Manager manager;
public void setManager(Manager m) {
if (m != null) {
this.manager = m;
}
}
}
Just in case it's not clear, you should add all the other methods you need. I only illustrated how to update the Manager reference in Employee when it's added to the List of direct reports.
You should also have a removeReport method that removes an Employee from the List and sets its Manager to null.
How do you intend to find an Employee in this List? By name? Employee id? Hint: think about overriding equals and hashCode properly for your classes.
Aren't Managers also Employees? Don't bosses have bosses? This is a hierarchy, a tree.
Usually a Object with different Attributes looks like this:
public class Employee extends EnterpriseMember {
private Manager manager;
private String name; // You probably don't need this because you defined it in the Superclass.
.
.
.
/*Constructor */
public Employee(String name){
super(name);
}
/*Methods */
public Manager getManager(){
return manager;
}
public void setManager(Manager manager){
this.manager = manager
}
// Other getters and setters for the attributes.
}

Acces linked list in main class from another class java

I have this project of an Online Store. The class OnlineStore is where the main method is, that starts the program. I also have 3 classes, User, Item andPackage, with some inherited classes.
I store all users, items and Packages in linked lists.
I created instances in the class OnlineStore inside the main method but I want to be able to access to them every moment; The class Item sould be able to access this linked list and remove an item that has been sold.
public class OnlineStore{
public static void main(String[] args) {
LinkedList<User> users = new LinkedList<User>();
LinkedList<Item> itemsSold = new LinkedList<Item>();
LinkedList<Item> items = new LinkedList<Item>(
LinkedList<Package> packages = new LinkedList<Package>();
}
}
//Then I create some instances of Items Users and call their methods of buying,
//loging in, etc..
//If a item is buyed:
public class Buyer extends User {
//ATTRIBUTES
private String accountNumber;
private LinkedList<Item> boughtItems;
//CONSTRUCTOR
public Buyer(String n, String id, String pass, String a){
super(n, id, pass);
accountNumber = a;
}
//METHODS
public void buy(Item i){
boughtItems.add(i);
//Here I need to acces the first class and remove from availableItems
items.remove(i);
}
}
Thanks for your help!
John R.
Try something like this:
public class OnlineStore{
public static LinkedList<User> users = new LinkedList<User>();
public static LinkedList<Item> itemsSold = new LinkedList<Item>();
public static LinkedList<Item> items = new LinkedList<Item>();
public static LinkedList<Package> packages = new LinkedList<Package>();
public static void main(String[] args) {
}
}

Creating a new instance of a class from another class

So I'm stuck on some homework trying to create an instance of the Employee class from my class called records.
public class Employee implements Comparable<Employee>
{
/* instance variables */
private String Name;
private String employeeNumber;
/**
* Constructor for Employee
*/
public Employee(String employNum)
{
super();
this.employeeNumber = employNum;
}
Next I need to create a Record class that will create a HashSet of Employees details, this is where I need help.
public class Records
{
private HashSet employeeSet;
public Records()
{
Set<Employee> employeeSet = new HashSet<Employee>();
}
Then I want it to have a method for adding a new employee and then putting their records in the set.
public enrollEmployee(String num)
{
Employee newEmp = new Employee(num);
employeeSet.add(newEmp);
}
}
I can't get that last bit to create a new employee, it doesn't come out with an error and it compiles correctly. Just no new employee.
*Adding the employeeSet.add(newEmp); caused a compiler warning and that method won't run due to a NullPointerException, probably because the employee isn't actually created.
For more info, when I create an employee the name should come out as "null" if only an employee number is entered but I still need to store that information.
Edited to update information. There is more detail for the Employee class which I have left out, I'm only supposed to be creating the Records class.
Last update, thank you for the help. After reading the replies this is what I got to work for me.
public class Records
{
private Set<Employee> employeeSet = new HashSet<Employee>();
public Records()
{
}
public void enrollEmployee(String num)
{
Employee newEmp = new Employee(num);
employeeSet.add(newEmp);
}
}
Heres the new solution based on what you are looking for in the comments
public class Record
{
private Set<Employee> employeeSet = new HashSet<Employee>();
public Record()
{
newEmployee("1");
newEmployee("2");
newEmployee("3");
}
public void newEmployee(String employNumber)
{
Employee newEmp = new Employee(employNumber);
employeeSet.add(newEmp);
}
}
The method that you created was never called on... So an employee was never created. Therefore, by calling on the newEmployee method in the Record Constructor, a new employee is created

Categories

Resources