public void setTo(String to) {
this.to = to;
}
public String getTo() {
return to;
}
What does above code do? In my project file I search for setTo function and there's no setTo() found, so how does it been called? and the this refer to?
In Object Oriented programming it is wrong for other classes to have access to some variables in your program simply because as you write larger programs some of your variables can be changed without your knowledge. To stop this we make the variables in your class private and create getters and setters. The first method is a setter which can set a private variable in your class to what the user wants. This will stop many errors from occurring. The
this
is a keyword which is calling the current class you are in. If the variable passed in as a parameter is the same as the private variable declared at the top of your class, we use this to refer to the variable at the top of the class.
This two methods are the setter-getter for the property to of your class.
You source code may not call these method but still these methods are called by some framework/third party library such as JSF, Spring those you are using in your project.
Looks like you have three questions. I'll answer them in order:
What does above code do?
These methods allow code from outside the class to set and retrieve the to variable value within the class, even if it's been declared private.
In my project file I search for setTo function and there's no setTo() found, so how does it been called?
Spring uses the setter methods to do dependency injection. Basically there's Java in Spring libraries that will automatically look for these variable names and call a corresponding method named after the variable, with 'set' in front of the name.
IDEs can generate both getters and setters automatically, and since you need the setters for Spring, people tend to also have the IDE generate the getters, even if they don't plan on using them.
and the this refer to?
this is a scoping keyword.
this.to refers to a variable named to that's part of the class where these getter/setter methods are. The 'to' without the 'this.' refers to the (String to) in the parameter definition, which is the one that a call would pass in.
Essentially, "Getters" and "Setters" are methods specifically designed to interact with Fields without directly manipulating the field. This is called " FieldEncapsulation"
https://en.wikipedia.org/wiki/Field_encapsulation
Instead of directly accessing a Field, you access it's methods. You can restrict usage in your code, i.e., not allow any getting, or setting, or both.
If you have access to the Field itself, you can do anything, but if you split up methods for the field, then you are able to
better manipulate the field actions.
make your code cleaner (text.setName(name) is easier to understand than writing text = "name";
restrict access to parts of your code (depending who is using your code).
Some pieces of code also use the getters/setters specifically, and not the fields, so making sure your fields have Getters/Setters is a good practice overall.
For example, Apache BeanUtils.copyBean() will NOT copy a bean if getters/setters are not set.
You asked what
public void setTo(String to) {
this.to = to;
}
public String getTo() {
return to;
}
means so instead of saying
String setTo = "hello";
or
String setTo2 = setTo;
you can do
setTo("hello");
or
String s2 = getTo();
So setTo requires a String parameter, and then will get our "to" field String to; to whatever is the value of the parameter.
getTo will then get our field to, and return it.
There are also instances where people will add additional code into the set/get statements, but I'm not sure how common that is.
Hope this helps!
These are Getter and Setter methods for a Class global String variable (or property) named 'to'. The related Class is usually the very same Class the getter and setter methods are contained in as is the variable they are related to. If you look at the top of the Class code just under the Class constructor you should be able to locate the String variable 'to', for example:
private String to = ""; // or something similar
Usually, if there is a variable named 'to' there is also another variable named 'from' (but not always) and it to may also have getter and setter methods contained within the class.
Getter and Setter methods allow you to retrieve and modify variable data contained within a Class from another Class during run-time, for example:
MySpecialClass myClass = new MySpecialClass();
// Use the 'to' variable getter to retrieve its current
// contents and place those contents into the 'toVar' variable.
String toVar = myClass.getTo();
// Display the contents...
System.out.println(toVar);
// Set the 'to' variable within the MySpecialClass Class
// to hold the string "I hold this now"...
myClass.setTo("I hold this now");
// Use the 'to' variable getter again to retrieve its new
// contents and place those contents into the 'toVar' variable.
toVar = myClass.getTo();
// Display the contents again...
System.out.println(toVar);
Now code contained within the MySpecialClass can use the 'to' variable with its new data value. You will notice that Java Class Libraries do things this way, very much the same as setting specific properties for a JButton or JLabel etc. etc.
Related
I would like every object of a class be able to access a class variable but don't want to get modified outside class.
For example the way Array.length is used.
But would also like to have a method in class which conditionally modifies this variable.
Basically this usage is for a resizing object array implementation, where length of object array can change dynamically.
There seem to be a few confusing points here.
I would like every object of a class be able to access a class variable but don't want to get modified outside class. For example the way Array.length is used.
Array.length is (effectively) a final field - an array's length in Java cannot change, so it cannot be modified from inside or outside the class.
But would also like to have a method in class which conditionally modifies this variable.
If a variable is final, as the length field in array, then its value cannot be modified at all, by anything.
You're not going to get this level of control from a field directly. Instead you should follow the standard getter pattern - make the field private and non-final, provide a public method to get its value (getLength() for example) and then set it as you need to within that class. This gives you the flexibility to change the value from within the class as you need to, while still allowing the value to be read from anywhere else.
Array.length is marked final and hence cannot be modified after the constructor is returned. I don't know what you're talking about there.
I guess, you want a private field with public getters and private setters?
private int someField = 0;
public int getSomeField() { return someField; }
private void setSomeField(int newValue) {
if (someCondition) {
someField = newValue;
}
}
Since both someField and setSomeField are private, no code outside of this class can modify the value of someField.
Code outside can only get the value of someField.
Code inside the class can conditionally set the value of someField by calling setSomeField.
Requirements met!
I think what I was trying to do could be accomplished by ArrayList implementation. Thanks for your replies.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I know this is very basic but I want to know why we should use private variable in encapsulation.I am mentioning my code. so I can give you better explanation.
Class Employee
{
private String eName;
public String getEname()
{
return this.eName;
}
public void setEname(String name)
{
this.eName=name;
}
Here "eName" is private so we can restrict outside object to access directly. variable can be access using its getter setter only.
Now my question is why we should use getter setter method? can't we declare variable as a public.?
Using setter method any one can change the value so what is need of this private variable?
Another Question
we set create read/write only method if we don't create getter method then it become write only and if we don't create setter method then it become read only.
so what is the use of read only and write only ?
If we don't create setter method then how value will set to variable ?
If we don't create getter method then how value will retrieve?
Please give me the answer of above simple questions.
Thank you
:)
The point of making variable private and
Let's say your bankBalance is a private variable and checkBalance() is a public method which is calling a public getter method getbankBalance() for bankBalance.
Now by doing this I can call checkBalance() which will call getbankBalance() function and read the value of bankBalance. I will only have read only access to sensitive data via a public method only.
Now, If the variable bankBalance is public any function can access and change the value of your bank balance, I can check for packageName.ClassName.bankBalance variable and then I can change the value of that variable to 0.
In order to provide read/write only accesses we need to make variables private, protected.
Hence The need of private variables in public methods.
Hope this is good explanation.
If we declare the method as public, then others can change its value. Sometimes, in encapsulation, you don't want the value to be changed, but only to be seen. public members can be read, as well as be changed. Hence, you declare it private.
so what is the use of read only and write only ?
I have rarely seen write only, but read only is common, for example, in bank account softwares. You want the account balance to be read, but not to be changed!
If we don't create setter method then how value will set to variable ?
obj.eName = "Whatever";
If we don't create getter method then how value will retrieve?
whatever = obj.eName;
in setter we can validate input data being set to property and take action accordingly, refer below :
public void setEname(String name)
{
//Here we can validate input data or even throw an exception
if(name!=null && name.length()<5){
this.eName="Some Default Value";
//throw new IllegalArgumentException("Your custom message goes here");
}else{
this.eName=name;
}
}
Also many api's use java reflection to set private property values, for this setter methods are required.
Now my question is why we should use getter setter method? can't we
declare variable as a public.?
Using setter method any one can change the value so what is need of
this private variable?
The public and protected methods of your classes form part of its exported API, i.e. the contract you make with client users of your class that specifies what your class does. In other words, the accessible methods specify your class's behavior.
The fields of yout class form its state. A class's state need not, and often does not, have a dependency on its contract. In other words, the fields in your class that are hidden away form part of your class's implementation (but not its behavior or its contract).
Note that the hidden parts of an implementation are not part of the contract and are also not part of the exported API. This means that you are free to change the implementation at any time without risk of breaking your client's programs as long as the implementation continues to obey the contract of your exported API. Therefore, fields that make up the state of your objects should nearly always be made private or package-private.
All this changes when you make your fields public. In this case, clients have direct access to your class's state and so now it becomes part of the exported API. Making fields public makes your implementation part of your contract and so now you are no longer free to make any changes to that part of it. You must continue to support that public variable for as long as your class exists.
Given this simplified scenario:
private String name;
private String getString() {
return "Hello, " + name + "!";
}
I would like to capitalize the name with a private static capitalize(String) method. If I extract name into a method (CTRL-2 + M), then I get a private String capitalize() method that references the name field.
Here's the desired result: (before implementing capitalization)
private static String capitalize(String name) {
return name;
}
I really want capitalize to be static, because I can then move it to some other class (SHIFT-ALT-V). Also, when there are multiple fields, moving them to parameters is tedious.
Is there any way to extract a method, or introduce an indirection that passes fields as parameters? It does not need to be a single refactoring; a combination might still save typing and human error.
Here's a sequence that would work:
Extract the field reference name to a new local variable (Alt-Shift-L), call it "toCap"
Extract a method from the reference to toCap, call it "capitalize"
Add modifier static to capitalize
Inline the extra local variable toCap (Alt-Shift-I).
Now you can move capitalize to the place of your liking.
For this exact scenario, it may not be worth it (simpler to directly create the static capitalize method), but I can see that in more complex situations this sequence of refactorings could actually help.
The general pattern behind this sequence is: before extracting a method, prepare all the arguments you want to pass into the method using fresh local variables. When the method has been extracted, inline the unwanted local variables.
Extract the part of the method that you want to become static. Yes, this will still refer to fields.
Make the new method static.
In the caller, pass the fields as parameters (use the warnings about fields not being accessible from the static method as a reference).
CTRL-1 the extracted method in the caller, and pick + Change method: Add parameter
The extracted static method should now have parameters that hide the fields because they have the same name.
I was wondering if it's possible to use a variable of a java class in another java class.Suppose variable Time is defined and calculated in Class A, how can I use it in Class B?
Other answers have suggested increasing a variable's visibility. Don't do this. It breaks encapsulation: the fact that your class uses a field to store a particular piece of information is an implementation detail; you should expose relevant information via the class's API (its methods) instead. You should make fields private in almost all cases.
Likewise, some other answers have suggested possibly making the variable static. Don't do this arbitrarily. You need to understand what static really means: it's saying that this piece of information is related to the type rather than to any one particular instance of the type. Occasionally that's appropriate, but it's generally a road towards less testable code - and in many cases it's clearly wrong. For example, a Person class may well have a name variable, but that certainly shouldn't be static - it's clearly a piece of information about a single person.
You should think carefully before exposing information anyway - consider whether there's a wider operation which the class in question could expose, instead of just giving away its data piecemeal - but when you do want to expose a field's value, use a property. For example:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
By exposing it via a method, you can later change the implementation details without breaking existing clients.
Then from another class, you'd just call the getName() method:
// However you end up getting a reference to an instance of Person
Person person = ...;
String name = person.getName();
If you do have a static field, you can expose the value in the same way, but with a static method, which you'd call using the class name.
Be careful about returning values which are mutable, e.g. java.util.Date. This is another reason for using a getter method instead of allowing direct access to the field - you can make the method return a defensive copy where you need to.
If it is declared as public, you may use ClassA.yourVariable. On the other hand, for private access modifier, include the getter to your ClassA. On the ClassB, call ClassA.getYourVariable().
Also read about access specifiers in Java it might help.
If the variable is static, you can refer to it as A.Time from any code that has access to the variable. There's only one Time value for all of class A. If it is an instance variable, and you have an instance a of class A, you can refer to the variable as a.Time. There's a separate value for each instance of class A.
This is subject to Java's access rules:
if the field is public, any code can access it (this makes public variables kind of dangerous unless they are also declared final)
if the field is protected, only code in the same package or in a subclass of A can access it
if the field has default access, only code in the same package as class A can access it
if the field is private, only code in class A (including inner classes of A) can access it.
Alternatively, you can provide an accessor method in class A:
public class A {
. . .
public class getTime() {
return this.Time; // the "this." is optional
}
}
If you declare your Variable as public or static you will be able to access it from another class.
WHICH IS A VERY VERY BAD IDEA :)
Hi apologies for the basic question, im sure I've been told the answer before and I've spent some time searching but couldn't find a good answer (probably because its hard to phrase as a search query), I've done a little bit of OO programming before but ive done a lot of procedural stuff recently so that seems to be clouding my thoughts.
I have a program that has to work with strings, part of that program involves sanitising a string, so I have this method:
private void sanitizeString() {
removeEscape();
removePunctuation();
removeCaps();
}
And earlier in the class declared the variable
String x = "... some string ..."
In procedural you would obviously pass all of the functions the string that they need to work on, my question is in OO is it ok to have this string declared at the top of the class and then just do something like
private void removeCaps() {
x = x.toLowerCase();
}
or should it be
private String removeCaps(String y) {
y = y.toLowerCase();
return y;
}
I think this it should be the first way, and I know that that works ok, but im doing something that has to demonstrate good OO so I just want to check I have my basic assumptions right.
Thanks
You have a trade off here:
Declaring the variable as a class variable means that you must create a new object for each String you want to sanitize.
Passing the String variable to each method means that you can reuse the same object to sanitize multiple Strings.
You must weigh the advantages and disadvantages of each approach to decide which is most appropriate for your particular situation.
Since x is declared as class variable, this one is fine:
private void removeCaps() {
x = x.toLowerCase();
}
as class variables are accessible inside class methods and you don't need to pass the class variables as arguments to same class methods
Same class variables are accessed this way only. Very simple example could be POJO classes, where you declare class variables and expose them through getter/setter methods. You don;t need to pass the class variables to these methods and some time, you can't(e.g. in getter methods).
Adding some thoughts around class variable vs. local variable in the method.
If there is a need of a variable which is theoretically associated with the class definition then the variable should be defined as class variable. e.g. employeeId, employeeName.. variables in a employee class should be defined as Employee class variables.
If there are variable needs which are local to a class method only and not required anywhere outside the method/class, then it should be defined as local variable inside the method.
If you are defining some utility methods to respond using some variables then those variables should be passed as argument to the util methods.
Back to your question:
If you are defining a entire class e.g. Sanitising, which has several methods around the string variable e.g. String class itself, then better to define your string as class variable and write the methods using the class variables.
But if you are defining Sanitising as a util/helper class then better to pass the string as method argument as normally you don;t want your util methods to be statefull (associated with the class instance).
To demonstrate good OO, you should definitly use
private String removeCaps(String y) {
return y.toLowerCase();
}
You can pass your Object, in this case your String in the global field x to the method as parameter. The String is then in the local field y and return the modified version.