Java getter() and setter() - java

can someone please tell me why I cannot use the Set properly? I managed with the Get to load the Name, Surname etc.. in the text boxes but the Set is not letting me read from the text boxes and save them. Thanks
custnameTF.setText(bookingfile.getCustomer().getPersonName());
custsurnameTF.setText(bookingfile.getCustomer().getPersonSurname());
customerbooking.setCustomer(.setPersonName(custnameTF.getText));
public class Booking implements Serializable{
private String flighttime;
private String flightlocation;
private String flightfee;
private boolean car;
private boolean insurance;
private Customer customer;
I'm trying to connect 2 classes together without an extend. I want to load and save on the Customer class through the Booking Class. Thanks

First in hand, that's not the correct syntax to set.
Since that setCustomer accepts only Customer object, you need to create a Customer object and then set it to bookingCustomer.
Customer customer= new Customer();
customer.setPersonName(custnameTF.getText); // look at the correct syntax.
//set remaining properties to customer objects from text fields
// ..
//then
customerbooking.setCustomer(customer);

Setters don't return anything in general, which is why you can't call another set method with the return value of another set method (returns void) as the argument.

Related

Find all RealmObjects that have inside a list a given RealmObject

Lets say I have this class (it already has an id property but it's already auto generated by realm):
public class User extends RealmObject {
private String name;
private String username;
}
And another one that has a list of Users inside:
public class Ride extends RealmObject {
private String tripName;
private String rideType;
private RealmList<User> usersJoined;
}
I just want to do a query to realm to get a list of Rides where the user is inside. I found another question like this but in that case the asker already has the object that have the whole list and he just need to find the user inside that spefic object property list, but in my case I want to get the Rides where the user (that I already know) is inside. Thank you in advanced!
Finally fixed using stream().filter :
RealmResults<Ride> rides = realm.where(Ride.class).findAll();
List<Ride> = rides.stream().filter(ride -> ride.getUsersJoined().contains(givenUser)).collect(Collectors.toList())

Update a current object given an object of the same type

Let us suppose we have the following class:
class Credentials implements ICredentials{
String name;
String surname;
String email;
public void update(ICredentials updatedCredentials){
// do stuff here
}
}
I would like to update the fields of the current class (the strings above) , using an object of the same type, without using getters or setters. Is there a way?
PS: noob here.
You could pass the object that you want to update to a ICredentials method that updates its content : updateParam(Credentials).
Add this method in the interface and Credentials that implements it could use private fields of the parameters as an instance of a class can access to private fields without getters.
class Credentials implements ICredentials{
public void update(ICredentials updatedCredentials){
updatedCredentials.updateParam(this);
}
#Override
public void updateParam(Credentials credentialsToUpdate){
credentialsToUpdate.name= name;
credentialsToUpdate.surname = surname;
credentialsToUpdate.email= email;
}
}
But this is convoluted enough.
The real issue in your actual logic is that you want to pass ICredentials as parameter that is not necessary a Credentials. In these conditions, the interface needs to provide a way to extract the name, surname and email information.
You don't have to consider these methods strictly as getters but as methods required to fulfill the interface contract.
Without it, to extract data from the interface you should do convoluted things or downcasting from the interface to the subclass or still worse...
Assuming that updatedCredentials is the same instance of Credential, one way is that you can directly assign
public void update(ICredentials updatedCredentials){
Credentials cred = (Credentials) updatedCredentials;
this.name = cred.name;
//rest of it
}
Remember you need to declare the variable as public. But this process is very ugly. If you can use getter and setter that could be nice solution and it is the best practice

In Java is it correct to allow subclass to alter superclass private fields via public setter method?

Please look at the code below
Class Employee{
private String name;
private String id;
public String getName(){ return name; }
public void setName(String name){ this.name = name; }
public String getId(){ return id; }
public void setId(String id){ this.id = id; }
}
Class Teacher extends Employee{
private double salary;
}
Now my question is If I am creating an object of Teacher , then it does not make sense without the Teacher object having a name and id. I can set the same for teacher object via public setters of Employee but it it correct ?
Teacher t1 = new Teacher();
t1.setName("aaa");
t1.setId("224");
t1.salary = 200.00;
System.out.println(t1.toString());
I am asking this question as my understanding is if the field is private it should be used only via getters . But in the example provided above Teacher object will not make sense without having a Name or Id .
If it is correct then why not make the field public in the first place? What is the advantage in using it private and then allowing access via public setter ?
If it is not correct please provide an example of how the above Employee and Teacher class should be implemented ?
Your question seem to show a confusion between two concepts rather independant:
encapsulation
creation of objects
Encapsulation: it is better design to define private variables. Then you can not corrupt the object from outside. You must use setter to modify your employee.
But, if you trust Teacher, it could modify Employee as a subclass, without setter, it is faster to code (but little risky: if you have to change the setter in employee, Teacher wont get it, ...).
Creation of objects: you should pass certain values to the variables, or they are defined by default (or auto-built ...)
=> you can decide that Teacher have well defined values (default), or that you must give these values (mandatory). It is your design.
After that, you can change them directly or by setters of Employee (=> first concept of encapsulation).
then it does not make sense without the Teacher object having a name and id. I can set the same for teacher object via public setters of Employee but it it correct ?
This is where exactly constructor comes into picture. You need to pass them before you are using it.
Thumbrule : When you want something while building it, you need to force them to pass on constructor.

Is it appropriate for a subclass to restrict it's parents member variables?

Is this an appropriate design? Is there an alternative?
package com.company.core;
public Foo{
private String appName;
public void setAppName(String appName){
this.appName = appName;
}
public String getAppName(){
return appName;
}
}
package com.company.application;
public Bar extends Foo{
private String appName = "MyFirstApp";
}
In my application Foo is an entity class for a table set up by our DBA. They are expecting a free-form field to identify the application storing information in that table. So we have a generic class that accepts a string.
Now in our application, we want to use that class, however the application name will always be the same and we want to enforce this. It's simple enough to hide the superclass's variable like this, but what do we do about the public getters and setters? Is there a better way to restrict the value of a field?
Yes it is appropriate and reasonable to restrict the values of an attribute in a subclass. In fact you can (and should) override the setter to thrown an IllegalArgumentException if the value attempted is not your specific value. No need to worry about the getter.

Should I create new class or use the existing one

I have the following BO which is already there in the system
public class userBO
{
private String userId;
private String password;
private String firstName;
private String midName;
private String lastName;
private String userType;
private String userDepartment;
private String userAuthority;
//There are some more fields
//getter and setter
}
Now I want to built a dropdown in which I will display Name (firstName + lastName) and will use userId as value. So for that I will make a list of object.
So my question is should I use the existing userBO class or should I create new class something like below
public class userDropDwonBO
{
private String userId;
private String firstName;
private String lastName;
//getter and setter
}
I want to know the answer from Good Architect point of view and also performance point of view, Will there be any better performance if I user new userDropDownBO
userDropDownBO object will definitely use less memory than the above class.
It is because all your members are private intance variable, everytime a constructor is invoked, a set of all private variables will be created on stack and will be initialized to their default values so will consume more memory and initialization time.
But it solely depend on your requirement:
If other fields are required other than these three fields go for the userBO class.
If other fields are unnecessary but no of objects to be created are small in number, go for userBO.
If other fields are unnecessary but no of objects to be created are very large in number, go for userDropDownBO.
Its a personal opinion and rest is your choice.
If you are going to create a new class beside the existing one named UserBO just for the sake of binding it to the JComboBox, that will definitely be a waste of memory and waste of time as well and also you will need to provide an additional logic to map your original object of type UserBO to the the object of type UserDropDownBO.
I would say that your approach maybe applicable in case the BO itself is so complex in dealing with, so that you need to create a separate model to be used in the drop down box.

Categories

Resources