Having troubles creating this object - java

I'm very new to java, and trying to grasp making an object with two different values.
I'm trying to create a Customer object called customer, with the initial values of 1 and cust1, and then display the customer object to the output with toString()
Thanks for any help in advance.
Here's what I have currently.
public class Customer {
private int id;
private String name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
Customer customer = new Customer(1, "cust1");
}

You have no entry point to your program, which should look like this in your class
public static void main(String[] args)
{
//objects created here
}
You also create a Customer object as a member of your Customer class which means every Customer object contains another.
You can't set Customer members like this
Customer customer = new Customer(); //you also don't have a no argument constructor
customer = 1; //how would it know where to put this 1?
customer = cust1; //same as above
it would be like this (if they were in the right place, as mentioned above)
Customer customer = new Customer(); //if using this method you will need a no argument constructor
customer.id = 1;
customer.name = cust1;
or like this
new Customer(1,"cust1");
In Summary
You need an entry point
You are creating Customer with a no argument constructor but you only have one constructor which has two arguments
You are -for some reason- creating a Customer inside every Customer
You are not setting members of your Customer object in the correct (or even in a valid) way

Don't create a new object instance within a classes constructor — this will result in a StackoverFlowException.
public class Customer {
private final int id;
private final String name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
In a separate class you can simply create a new instance by using
Customer customer = new Customer(1, "Name");

Related

How to return a class using the constructor in java?

How to return this Customer class so i can use this class in another class.
If i use static instead of void then i am unable to call customer Transaction from the constructor.
I tried writing new keyword but it did not work but this is returning a class:
import java.util.ArrayList;
public class Customer {
private String name;
private ArrayList<Double> customerTranscation;
public Customer(String name) {
this.name = name;
this.customerTranscation = new ArrayList<Double>();
}
public String getName() {
return name;
}
public ArrayList<Double> getCustomerTranscation() {
return customerTranscation;
}
public void newCustomerTran(String name,double amount){
this.customerTranscation.add(amount);
this.name = name;
}
}
How can I return Customer class so I can use this in another class?
In you second class, You got to create the object of the customer class first .
Like Customer c=new Customer(“abc”);
This is going to initialise the CustomerTransaction List.
Then call c.newCustomerTrans(“name”).which will invoke the newCustomeTrans method from your second class.
If you want an customer object to be returned . Do .!
public Customer newCustomerTrans(String name ,double amount){
//create a new object p of Customer using new
//set name to p
//initialise and set customer trans arraylist to p
// return p
}
This way you can use Customer class details from your second class..

To define an object in a constructor in Serializable class

I have a JSON response like below image, and I have made a serializable class named as Project
In the image, I have two objects (emergency_contact, and secondary_owner) inside my an array of one object. I'm trying to figure out whether what to do in order to define the object, since I want that details to be present inside my constructor.
I have done this so far:
public class Project implements Serializable {
public int id;
public String name;
public String additional_information;
//Now what to do Emergency contact
public Project(int id, String name, String additional_information){
}
}
I have thought of doing this, public EmergencyContact emergency = new EmergencyContact(param1, param2).
And make a new class named as EmergencyContact, and do a getter and setter for the params. But after doing this, I'm still confused, how would I define it my constructor?
I know I'm close, but I need some help on that.
Sure. You need to have a:
public class EmergencyContact implements Serializable {
public String name;
public String number;
public EmergencyContact(String name, String number){
// assign fields
}
}
and one for the owner:
public class EmergencyOwner implements Serializable {
public String name;
public String number;
public EmergencyOwner(String name, String number){
// assign the fields
}
}
then in your Project class you can add fields of these classes:
public class Project implements Serializable {
public int id;
public String name;
public String additional_information;
public EmergencyContact emergency_contact;
public EmergencyOwner emergency_owner;
public Project(int id, String name, String additional_information, EmergencyContact emergency_contact, EmergencyOwner emergency_owner){
// assign the fields here as well
}
}
that's it. If that's an answer to the question consider to delete this question as it is a duplicated on a 100% :)
As a note, to be correctly from the point of clean code parameters, the fields should be private in a class, and use setters / getters to set/retrieve values from/to those fields.
public class Project implements Serializable {
private int id;
private String name;
private String additional_information;
private EmergencyContact emergency_contact;
private SecondaryOwner secondary_owner;
public Project(int id, String name, String additional_information, EmergencyContact emergencyContact, SecondaryOwner secondaryOwner){
this.id = id;
this.name = name;
this.additional_information = additional_information;
this.emergency_contact = emergencyContact;
this.secondary_owner = secondaryOwner;
}
}
You will define the other two classes the same way. Now, you are probably confused about the constructor of EmergencyContact & SecondaryOwner classes.. You can device both default constructors (without parameters) and a custom one(with parameters to it, just as the one above). If you use the default constructor, make sure to set values to the fields in the object, as following :
EmergencyContact emergencyContact = new EmergencyContact();
emergencyContact.setName("the name");
emergencyContact.setNumber("a number");
then you can use this object in the constructor of Project class
I hope it was clear enough, for any other clarifications feel free to ask.
Happy coding <3

Adding objects to an Array in a class from a test file?

Unsure on how i'm supposed to add to an array, i've been asked to fill the array from a test file but define it in class Patient. Any ideas?
public class Patient
{
private String name;
private int id;
private int current = 1;
public Patient(String name, int id)
{
this.name = name;
this.id = id;
Patient[] patient = new Patient[100];
String[] Observations;
System.out.print(patient[0]);
}
public String addPatient(String name,int id)
{
Patient[current-1] = new Patient(name,id);
}
}
// extract from class PatientRecordSystem
public void addPatient()
{
String name = "James";
int id = 10122;
Patient patient = new Patient(name, id);
}
Your problem is that you are defining that list (or array) to hold Patient objects within the constructor of your Patient class.
That is simply wrong on many levels. First of all - one "Patient" should be exactly that - the representation of a single patient. When you go to the doctor and become a patient ... are you asked to know about 100 other patients around?! Then: that array that you define in the constructor ... just lives during the execution of the constructor. It simply goes away as soon as a call
Patient newPatient = new Patient( ... )
returns.
In other words: you want to think of another class that is responsible for "managing" multiple patients. And then you create "patient objects"; and tell the manager about them. And that "manager" is then using an array (or better some more dynamic List) in order to keep track of "managed" patients.
Whatever Andrew said is correct , just making it easy for you. Use below code
public class Patient
{
private String name;
private int id;
private int current = 1;
private Patient[] patient = new Patient[100];
public Patient(String name, int id)
{
this.name = name;
this.id = id;
String[] Observations;
System.out.print(patient[0]);
}
public String addPatient(String name,int id)
{
patient[current-1] = new Patient(name,id);
}
}
// extract from class PatientRecordSystem
public void addPatient()
{
String name = "James";
int id = 10122;
Patient patient = new Patient(name, id);
}
First you need to declare the array.
You can do something like:
Patient[] patients = new Patient[100];
if you know the size of the array.
If you want to build a dynamic array, because you don't know how many elements you are going to have, you can do something like that.
List<Patient> patients = new ArrayList<Patient>();
Then you can assign values to the array:
If you have declared a fixed array you can do something like that:
patients[0] = new Patient(name, id);
On the other hand, if you have declared a dynamic array, the code would look like:
patients.add(new Patient(name, id));

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 ();
...

Wondering if I'm doing this immutability exercise correctly

My professor just went over mutable and immutable, and gave us this coding exercise to complete.
1) Create a Customer object called customer with initial values of 1 and "Cust1"
respectively.
2) Display the customer object to the screen using the toString() method.
3) Create a String object reference called name and assign to it the customer's name.
4) Assign the value "Bo Beep" to the object reference name.
5) Display the customer object to the screen using the toString() method.
The output should look like this.
Customer{id=1, name=Cust1}
Customer{id=1, name=Cust1}
I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.
Any input is helpful, thanks!
Here's my main class,
package hw01;
public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");
public static void main(String[] args) {
System.out.println(customer);
System.out.print(customer);
}
}
And here's my Customer class.
package hw01;
public class Customer {
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + '}';
}
}
Sounds like for #3 it should be something like this:
String name = customer.getName();
and then #4 would be:
name = "Bo Peep";
The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".

Categories