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 ();
...
Related
I need to check if an object in an ArrayList exists by using a method with given parameters. The method that I have will take parameters related to the values of an object of an object in the classes ArrayList.
Customer has an ArrayList of Transaction type. Transactions have a field, Service, that is an ArrayList.
the Service class has the following fields ServiceType(enum) serviceName, double price and an Arraylist of type Employee called machanics.
In the customer class, I tried accessing the getters from the service class to compare with the parameters that are passed to the method "findTransaction". I'm getting "Cannot resolve Symbol" so I'm sure that is not how go about doing this. I can't figure out how to check the values for the Service ArrayList object from the customer class to compare them with the parameters that are passed from "findTransactions". I could be going about this all wrong by trying to evaluate equivalency in ArrayLists in ArrayLists in ArrayLists to passed parameters, but I'm not sure.
CUSTOMER CLASS
public class Customer {
private String name;
private String address;
private int phoneNumber;
private ArrayList<Transaction> transactioins;
private ArrayList<Car> cars;
public Customer(String name, String address, int phoneNumber, String carMake,
String carModel, int manufactureYear) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.transactioins = new ArrayList<Transaction>();
this.cars = new ArrayList<Car>();
createNewCar(carMake, carModel, manufactureYear);
}
public boolean createNewTransaction(ServiceType serviceName, double price,
Employee mechanic, String mechanicName){
this.transactioins.add(createNewTransaction(serviceName, price, mechanic, mechanicName));
return false;
}
private Transaction findTransaction(Service serviceName, double price, Employee mechanic){
for(int i=0; i<this.transactioins.size(); i++){
Transaction chkedTransaction = this.transactioins.get(i);
if(chkedTransaction.getServices(getServiceName, getPrice, getMechanics).equals(serviceName, price, mechanic));
}
}
TRANSACTIONS CLASS
public class Transaction {
private ArrayList<Service> services;
public Transaction() {
this.services = new ArrayList<Service>();
}
public ArrayList<Service> getServices() {
return services;
}
//when called service will be creted with new
public boolean createNewService(ServiceType serviceName, double price,
Employee mechanic, String mechanicName){
Service existingService = findService(serviceName, price, mechanic);
if(existingService == null){//MAKE A CREATE EMPLOYEE METHOD
Service newService = new Service(serviceName, price);
newService.createEmployee(mechanicName);
this.services.add(newService);
// this.services.add(new Service(serviceName, price, new Employee(mechanicName)));
}
return false;
}
// to see if the service exists
private Service findService(ServiceType serviceName, double price,
Employee machanic){
for(int i=0; i<this.services.size(); i++){
Service chkdServise = this.services.get(i);
if(chkdServise.getServiceName().equals(serviceName) &&
chkdServise.getPrice() == price &&
chkdServise.getMachanics().equals(machanic)){
return chkdServise;
}
}
return null;
}
SERVICE CLASS
public class Service {
private ServiceType serviceName;
private double price; //might need to use a link list double
private ArrayList<Employee> machanics;
public Service(ServiceType serviceName, double price) {
this.serviceName = serviceName;
this.price = price;
this.machanics = new ArrayList<Employee>();
}
public boolean createEmployee(String name){
Employee existingEmployee = findEmployee(name);
if(existingEmployee == null){
this.machanics.add(new Employee(name));
return true;
}
return false;
}
private Employee findEmployee(String name){
for(int i=0; i<machanics.size(); i++){
Employee chkedEmployee = this.machanics.get(i);
if(chkedEmployee.getName().equals(name)){
return chkedEmployee;
}
}
return null;
}
from what i gather you try to compare service objects in the transactions
i would implement a custom comperator object that compares service objects based on the fields that you want to use,
then create an object containing the parameters you have then iterate through it
using your code it would look something like :
class ServiceComperator implements Comparator<Service>{
// Overriding the compare method to sort the age
public int compare(Service s1, Service s2) {
if (s1.field==s2.field&&s1.field1==s2.field1 etc...)
{
return 0;
}
else
{
return -1;
}
}
and your comparing method:
private Transaction findTransaction(Service serviceName, double price, Employee mechanic){
ServiceComperator comperator=new ServiceComperator();
Service dummyService=createDummyService();
for(int i=0; i<this.transactioins.size(); i++){
Transaction chkedTransaction = this.transactioins.get(i);
List<Service> services=chkedTransaction.getServices(getServiceName, getPrice, getMechanics);
for (Service currentService : services) {
if (comperator.compare(dummyService, chkedTransaction.service())==0)
{
//they are equal do something
}
else
{
//they arent do something else
}
}
}
}
private Service createDummyService(params)
{
//create a service object based on the fields you want to compare
}
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..
I have set of objects of different types.
Ex : Employee emp, adress adr
These two classes have list of properties
public class Employee{
private Stringname;
private int age;
}
public class Adress {
private String HouseNo;
private string Street;
private string pin;
}
Each attribute is assigned with some 2 character value
Name (NA), age (AG), HouseNo(HN),Street(ST), pin(PN)
I need to construct a string with these data and delimit with a %
Output:
NA%Vidhya%AG%30%HN%80%ST%1st cross%PN%100100
Each class knows it own data best so I would let each class be responsible for generating the string. As I understand it the two char codes for each field are unique for each class and member and only used when generating the string so only the class would need them.
interface AttributeDescription {
String generateDescription();
}
public class Employee implements AttributeDescription {
//members...
public String generateDescription() {
return String.format(“NA%%%s%%AG%%%d”, name, age)
}
Then simply call this method for all objects implementing the interface.
AttributeDescription object = ...
String attr = object.generateDescription();
I don't think it can be generalized more than this given the requirements.
Update
It might be better to have a builder class for building the string to get a more unified behavior between classes. Here is an example
public class AttributeBuilder {
private builder = new StringBuilder();
public String getAttribute() {
return builder.toString();
}
public void add(String code, String value) {
if (value == null) {
return;
}
builder.append(code);
builder.append(‘%’);
builder.append(value);
builder.append(‘%’);
}
}
And then you would also have to implement add(...) methods for other data types in a similar fashion. The builder could then be used like
public String generateDescription() {
AttributeBuilder builder = new AttributeBuilder();
builder.add(“NA”, name);
builder.add(“AG”, age);
return builder.getAttribute();
}
I was trying to understand how constructors work and came up with two questions. I have two classes, one for an address and another for a person. the Person class has two Address objects in it. Here is a simplified example of what I'm doing:
private class Person{
private String name;
private Address unitedStates;
private Address unitedKingdom;
Person()
{
this.name = "lary"
}
Person(String n)
{
this.name = n;
//Can I call Address(string, string) here on unitedStates and unitedKingdom?
}
}//end of person class
private class Address{
private String street;
private String country;
Address()
{
this.street = "1 Washington sq";
this.country = "United States";
}
Address(String s, String c)
{
this.street = s;
this.country = c;
}
}
}
If I leave Person() as is, will it fill the the values for unitedStates and unitedKindom with "1 Washington sq" automatically?
And
Can I pass arguments for the Address object where I left that comment in the example?
Fields of an object will always automatically be set with a default value, if not initialized by yourself. The value depends on the data type of the field (see here https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). The default value of a field that represents an object is null.
Since you didn't initialize the fields unitedStates and unitedKingdom, their values will be null. What you can do is initializing the fields inside the Person constructors:
Person()
{
this.name = "lary";
this.unitedStates = new Address();
this.unitedKingdom = new Address();
}
Person(String n)
{
this.name = n;
this.unitedStates = new Address("myStreet", "myCountry");
this.unitedKingdom = new Address();
}
You could also use one constructor in another with the keyword this. Note that I have added a third constructor that is called by the other constructors:
Person(String n, Address unitedStates, Address unitedKingdom)
{
this.name = n;
this.unitedStates = unitedStates;
this.unitedKingdom = unitedKingdom;
}
Person(String n)
{
this(n, new Address("myStreet", "myCountry"), new Address());
}
Person()
{
this("lary", new Address(), new Address());
}
Address field are just initialized as null. you have to assign it an Address instance, in User constructor for example, like
unitedStates = new Adress();
wich will call the Address's constructor with no parameters.
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");