How to auto generate Getter() below the variable in IntelliJ IDEA? - java

this seems to be a very silly problem but I really have no idea how to deal with it. I'm using IntelliJ IDEA to write java code. Let's say my class have a variable name:
public class city {
private String name;
}
And I want to generate a Getter() method for name, the most convenient way is to use the auto generate:
However here is the result:
public class city {
public String getName() {
return name;
}
private String name;
}
As you can see, the getName() is always generated above the variable, but I want it to be below the variable. What should I do to achieve that? Thanks.

It depends on the position of the cursor. so where you click to generate the getter, it will create the code. to solve this. Just move the cursor under the attribute and click Alt + Insert
Then the result is:

Related

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.

Java getter() and setter()

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.

Display String based on user system language in Android

I have an enum class, but I want to display string based on user system language. For example, If the system is English , it should display 1 , 2 ,3
. But if the System is Chinese, the display should totally be different like "一", “二”, “三”. (一 means 1 in Chinese, 二 means 2 in Chinese).
Here is my code
public enum OrderType {
ONE("1"), TWO("2"), THREE("3")
private String name;
private OrderType(String name) {
this.name = name;
}
public String toString() {
return name;
}
public static String getEnumByString(String code) {
for (OrderType e : OrderType.values()) {
if (code.equals(e.name)) {
return e.name();
}
}
return null;
}
}
The enum works fine in android, Can I define the String in the value folder,
Like values-iw, values-ru... And how can I use that?
UPDATE:
I also want to use constructor to initialize the enum string. Just like
private OrderType(String name) {
String temp = getResources().getString(R.string.name);
this.name = temp ;
}
But I do not know how to pass parameter of R.string.parameter..
Second, how Can I use getResources() function in enum class
Just provide the String resource ID as a parameter to your Enum:
public enum OrderType {
ONE(R.string.order_type_one),
TWO(R.string.order_type_two)
private final int mTextResourceId;
OrderType(int resourceId) {
mTextResourceId = resourceId;
}
public int getTextResourceId() {
return mTextResourceId;
}
}
Provide these strings in each desired resource folder, e.g.:
res/values/strings.xml
res/values-es/strings.xml
res/values-fr/string.xml
Then, when you want to consume this in a TextView somewhere:
myTextView.setText(myOrderType.getTextResourceId());
No Context passing required, and it is determined at runtime based on the current locale.
You must know that enums are initialized statically. Each of ONE, TWO, THREE is static.
In android to use resources, such as strings, you need a context.
Generally, you can not access Android context in static methods or initializes, therefore you can't use them with enums.
Even if you could use a hack to make android context statically available you would still have issues :
you'd need to ensure none of your OrderType enums accessed before Application#onCreate
strings in your enums won't reflect runtime language changes
Edit
I hope it is clear that you can not reliably initialize your enums with string resources.
You could, however, associate static id of a string (R.string.string_name) with your enum and obtain needed resource string later using a context, as proposed in kcoppock's answer.
You should keep the strings in your string xml resource. That way you can get it from there into your code. For example like this:
String one = getResources().getString(R.string.num_one);
Then you just put a strings.xml file with overloading values in the language folders you want (values-ru, values-sv etc.)
For tasks of that kind use localizations.
"google on i18n java"
and
"android app localization"
public enum OrderType {
One(mActivity.getString(R.string.One)), Two(mActivity.getString(R.string.Two));
private String name;
private OrderType(String name) {
this.name = name;
}
public String toString() {
return name;
}
public static String getEnumByString(String code) {
for (OrderType e : OrderType.values()) {
if (code.equals(e.name)) {
return e.name();
}
}
return null;
}
}
also Here is the link, which I think is best way solve the porblem. This developing for API level 11 currently, however this code should run on higher versions. After a quick review in API 16 I did not see an existing core Android solution to this problem, if you know of one please post below and share.

Android Programming Question

Howdy, I am a programmer that has worked almost exclusively with c++/c#/vbs and am just now entering into the world of Android development. I am running into a few issues that I cant seem to find answers for/ dont want to watch lengthy tutorial videos to find out so I figured I would ask here and get a quick answer.
I dont know if this is the best way to do this, so I am open to any suggestions.
I need some custom data containers for my program, lets say I want an 'Achievement' class so I can have an array of them!
now in C# I would do something like
public class Achievment
{
bool locked;
string achName;
string achSubName;
public Achievement(string name, string subname)
{
//ctor code goes here
}
}
Thats not everything I would need but thats the idea of the data layout I would like. However when I try to make a custom class in Eclipse it is all up in my grill about 'Public type achievement must be defined in its own file?' I'm writing this in the application's .java file... Is there somewhere else this should go? I am so confused. Basically java may as well be swahili to me... I like my intuitive c# layouts!
Like essentially I want to store my data separate from my UI, and when I generate an 'Achievement List' it looks at the current user's achievement array and populates from there. Good, bad?
Any answers that are not in the form of a redirect to a tutorial are much appreciated!
You should define the Achievement class in a separate file, called Achievement.java. You also need to change the constructor to have the name name as the class:
...
public Achievement(String name, String subname)
{
//ctor code goes here
}
...
In Java, the type is String, not string.
You either have to remove public modifier from the class (thus its visibility will be default level -- visible only from the package your Application class is placed) OR you need to move your class to Achievment.java file.
In java, public classes are required to be in their own file with the name of the file being the same as the class name (in your example, it must be in Achievment.java).
Create a file called Achievement.java within the source folder in your Eclipse Java project. You would also likely want the class to exist in a package so your assuming your package name was "com.acme", then your Achievement.java file would exist within the following directory structure:
<project-folder>/src/com/acme/Achievement.java
Now, assuming you've done the steps above, you will also need to make the following corrections to the code you posted:
package com.acme // NOTE: This maps to the directory structure
public class Achievement {
private boolean locked;
private String achName;
private String achSubName;
public Achievement(String name, String subname) {
this.achName = name;
this.achSubName = subname;
}
public boolean isLocked() {
return this.locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public String getName() {
return this.achName;
}
public void setName(String name) {
this.achName = name;
}
// etc ...
}

Categories

Resources