Setters and Getters
Can any one Explain the setters and getters and different ways of writing?? How Can we use it much better??
http://www.flashscript.biz/flashas3/AS3_tutorial/lesson9.html
Similar Messages
-
How to use setters and getters in another program by using bean
how to use the setters and getters methods using database connection by bean
Say again?And so he did:
http://forum.java.sun.com/thread.jspa?threadID=750645
kind regards,
Jos ;-)And again
http://forum.java.sun.com/thread.jspa?threadID=750643&tstart=0
No, that's his class mate I guess; it must be national getter and setter
day somewhere today ;-)
kind regards,
Jos -
Hi All,
1. How parametters we can send to a Setter ?
2. What are the best practices of setters and getters?
Thank you
SivaYou should read up on "ENCAPSULATION". Here is a good read for ya:
http://www.inf.ufsc.br/poo/smalltalk/ibm/tutorial/oop.html
Thanks. -
Setters and getters in my beans - syncrhonize
All,
have a bunch of POJO's. Using hibernate. Should I syncronize my setters and getters?It depends if you would use the object concurrently or not. Even if you did use an instance concurrently, you would not need to synchronize on every getter and setter. I strongly suggest you learn the ins and outs of thread safety before arbitrarily locking your objects.
-
Why use setters and getters?
Hi.
I've been wondering woudn't a function with return do the same thing as a get function with return?
Ex:
var age:Number = 16;
function get Age() {
return age;
isn't the same as:
function Age() {
return age;
Thanks.I respectfully disagree with the statements that it is a matter of nomenclature. Although there are a lot of cases when accessors (getters/setters) are overused, they are definitely extremely useful features of any OO language. In some case code would be much longer and more cumbersome without accessors. I must say that with code written on timeline accessors are less useful (although I can see plenty of cases one can utilize them). When code is written in classes - accessors are indispensable.
With your age example it is really a matter of preference. But if you need to do more with age - you would definitely appreciate getters/setters.
For example:
Say you have a class Person and it has property age:
public var age:int = 0;
Somewhere we instantiate this class:
var myPerson:Person = new Person();
Now we set age:
myPerson.age = 23;
trace(myPerson.age); // returns 23
Just imagine you instantiate this variable in 100 of places.
When you think you are done, your boss comes to you and says: “I want you when they set the age also to evaluate what age group person belongs to.”
If there were no getters/setters – you would have a very hard time chasing all 100 instances in your program and changing your Person class architecture. With accessors you will spend a few minutes only. You can do the following:
// change the variable to private
private var _age:int = 0;
// create accessors
public function set age(a:int):void{
_age = a;
// here you evaluate age
if (_age < 10) {
trace("child");
else if (_age > 10 && _age < 20) {
trace("teenager");
else if (_age > 20 && _age < 30) {
trace("young");
else {
trace("too old to bare :-(");
public function get age():int{
return _age;
As you can see you changed the code in one place and while not doing a thing in any of 100 places you instantiated the Person class.
Again, your boss can come back and ask to restrict the age to people older than 20.
So may write:
public function set age(a:int):void {
if (a > 20) {
_age = a;
Again, you met requirements and did not change any code anywhere else.
One more request from the boss. Say, he wants you to count how many times age was changed. You can use setter to do that:
private var getterCounter:int = 0;
public function get age():int {
getterCounter++;
return _age;
You wouldn’t be able to do all these things if there were not accessors.
Still the use of age variable will stay the same:
var myPerson:Person = new Person();
myPerson.age = 34;
trace(myPerson.age);
Welcome to scalability and encapsulation. It doesn’t matter what you do when age is set inside Person class – it will not break code anywhere else.
There are millions more useful cases when getters/setters come handy. -
Bean - setters and getters naming conventions
Hi,
Just like the constructor is named after the class,
why shouldn't the setters & getters be named after the
properties?
This would make the reflection code clearer.
Wouldn't it?Maybe he means that they should be called:
void variableName(int value); // setter
int variableName(); // getter
Ouch, that was really ugly :)If thats true, our friend is a Delphi programmer :)
Next we could drop the parenthesis in no arg methods
v = variableName;
ahhhh, so much more obfuscating. -
How to use javasetters and getters in different classes
how to use setters and getters in different class so that the setvalue in one class is effect in second class for getting
If i got your question right,
make sure your classes are in the same package
make sure your getters are public/protected
make sure your code calls the setter before calling the getter
Kind regards -
Command Link : Backing bean setters/getters always invoked
I am trying to understand how to the setters and getters of a request scope managed backing bean are invoked through the navigation flow when using a command link.
It seems that no matter where the navigation rules redirects the page as a result of the action, both the setters and getters of any field bound in the originating page are called.
For example if the originating page has a field name referred by "#{UserBean.name}" to input a username. setName() and getName() are always called as a result of a click on a command link
This behavior is easily seen in a simple JSF example such as http://www.netbeans.org/kb/articles/jAstrologer-intro.html.
If the jsp pointed by "to-view-id" is changed to have no reference to the backing bean or is changed to a jsp with just text, both setters and getters are still invoked.
I could understand why the setters would be invoked (doesn't know ahead of time if the bean will be used?) but at least why the getters?
Last, how to prevent this behavior? The problem is that the backing bean might have complex logic where it will fetch data if a getter is called.
Thanks.I guess this article might be interesting to get some insights http://balusc.xs4all.nl/srv/dev-jep-djl.html
The setters are invoked to set values and the getters are invoked to get the eventually presetted default values or the previously submitted values. -
Custom component/tag class: ---which setters/getters do what?
Hi
I'm trying to create a custom component, but, there is a major concept that I do not understand...
---What are the setters/getters in the "component" class used for?...
---What are the setters/getters in the "tag" class used for?
Another way of asking is...
---Which setters/getters are used simply to keep track of attribute name/id/key?
---Which setters and getters refer to the actual objects that the attribute names point to?
The reason for my confusion is that nearly all "custom component" examples I've seen thus far, utilize attributes that point to "String" objects... (i.e., as opposed to ArrayList, HashMap, etc)...
This makes it difficult for me to distinguish whether the String values in the getters/setters are referring to the String name/"id" of the attribute...or, the String "value" of the attribute...
I have not been able to verify how I should code the getter/setters (and type casts) for other kinds of objects like ArrayLists, HashMaps, etc
For example, a typical logic mechanism Ive seen in the custom "tag" examples is as follows...
in a "tag" class...
if( tabledata != null )
if (isValueReference (tabledata))
FacesContext context = FacesContext.getCurrentInstance ();
Application app = context.getApplication ();
ValueBinding vb = app.createValueBinding (tabledata);
component.setValueBinding ("tabledata", vb);
else
component.getAttributes ().put ("tabledata", tabledata);
in the "component" class...
public void setTabledata (List tabledata)
this.tabledata = tabledata;
public List getTabledata ()
if(null != tabledata)
return tabledata;
ValueBinding _vb = getValueBinding ("tabledata");
if(_vb != null)
return (List)_vb.getValue (getFacesContext ());
else
return null;
}...considering the above code,
---when/where should the "tabledata" variable be referring the "name/id" of the attribute?...
---when/where should the "tabledata" variable be referring to the "value" of the attribute?...
...as, I need to change the type casting to adjust to what it should be...
***NOTE: This is one error that I'm getting, and I believe it is because I do not understand how getter/setter is used in "component" and "tag" classe, i.e., :
"org.apache.jasper.JasperException: jsp.error.beans.property.conversion
org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromPropertyEditorManager(JspRuntimeLibrary.java:885)"...
Thanks for any help on this!
sdThe "tabledata" variable always refers the local value of the attribute.
When using a value binding to some backing bean,
the local value is null and the model value is owned by the bean.
You don't need any casting in the tag class nor the component class.
The setters/getters in the component class specify the type of the attributes.
Conversion from/to String to/from the type is done automatically if possible.
When the automatic conversion is impossible, you should specify f:converter
for the attribute. -
How to pass the JCO Table and Structure in a collection List to frontEnd
hi,
I have a BAPI which is returns me a Table and a structure. As i have used JCO I will receive it in JCO Table and JCO Structure. Now the question is that how I should pass both these of these using a collection to the frontend for displaying the data from it.
Thanks' & Regards,
SamirHi Samir,
As you are trying to pass the Table and the Structure in the form of collection to the JSP page, you can create a javabean with the structure similar to that of the table/Structure.
Lets assume you have a table called Employee with Emp_Name, Emp_Age, Emp_Sal as three columns, create a java class by name Employee which implements Serializable and attributes as Emp_Name, Emp_Age and Emp_Sal. Generate the setters and getters for the same. In your EJB code, create an instance of this Employee class and set the attributes and save it in a HashMap in the form of key value pair, Value being your Employee class instance and key be your Employee Name. Return the HashMap in your EJB code.
Use the HashMap in your JSP. Get the Iterator for the HashMap and Loop through the keys to get the values.
Hope this helps.
Regards,
Rekha Malavathu -
What is exact diff between Bean and Class
As my knowledge...
Class should not depends on any specified rules..But Bean should specified on specified rules, like setters and getters....
is there any more........
thanks for giving help..........Yes, but what are they good for, except for providing
examples of really bad OO design by just being a
complicated struct?Look at Spring; an extremely powerful application configuration tool (and much, much more); all possible because of JavaBean conventions. Otherwise Spring would have had one set of conventions, JSF another, Hibernate another still, making programmers' lives difficult.
Look at the PropertyEditorSupport class - it's fantastic that I can write a standardized String-to-instance-to-String class for a particular type and just have frameworks like Spring take care of the problems generating my domain model from configuration. Using a standard mechanism makes me confident that if, in the future, I ditch Spring, my bespoke property editors will not be obsolete. -
Question about Struts and ActionForm
Hi,
I've a LoginForm class that extends ActionForm and the login.jsp page accepts 2 fields - "username" and "password" and there are corresponding setters and getters in LoginForm.java. As part of moving this to container managed security (using login modules), I want to change the field names to j_username and j_security. I made the change to the login.jsp page and also to the getters and setters (made them getJ_username, getJ_password) but I keep getting the "getter is not defined" struts related error. any thoughts?You would need to follow naming convention. It should be
userName,
I never tried with underscore, try j_userName (caps N). I don't think it will work. -
I have too many books and not enough understanding on this subject.
I am trying to fill an object type array with values and am totally confused. In my application, I successfully create a constructor in one file and test the object with some values in another file. I have two objects for employee and would like to place the object values into an object array. There is plenty of information on int[] arrays, but little on object arrays.
After I can do the array fill:
I would like to provide object values with JOptionPane.
Change the print display to show all array elements
But one thing at a time.
I was thinking that objects exist first, then are loaded or filled into an object array. I seem to misunderstand as I am not performing the array fill very well. Following a book example seems to confuse me only more.
Thank you
//emp.java
import java.util.*;
public class Emp {
private int id;
private String name;
private double salary;
public Emp(int ident, String nm, double sal) {
id = ident;
name = nm;
salary = sal;
// method raise salary by 5 percent
double raise() { return salary * 1.05;} // ends raise method
// setters and getters
public String getName() { return(name); }
public double getSalary() { return(salary); }
public int getID() { return(id); }
public void setName(String nm) { name = nm; }
public void setSalary(double sal) { salary = sal; }
public void setID(int ident) { id = ident; }
}The test file
//EmpTest.java
import javax.swing.JOptionPane;
public class EmpTest {
public static void main(String[] args_) {
// Create object based on EmployeeTest2 class
// to add employee data to the array called empArray
Emp emp1 = new Emp(1,"Smith",2000);
Emp emp2 = new Emp(2,"Jones",2500);
//test and confirm the objects emp1 and emp2
int i;
String n;
double s;
double newsal;
// get the salary after the 5 percent raise
i = emp1.getID();
n = emp1.getName();
s = emp1.getSalary();
newsal = emp1.raise();
System.out.println("object Employee 1 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: " + newsal);
i = emp2.getID();
n = emp2.getName();
s = emp2.getSalary();
newsal = emp2.raise();
System.out.println("object Employee 2 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: " + newsal);
// get the number of employees with JOptionPane
String employeeCountString = JOptionPane.showInputDialog(
"Employee Database " +
"\nEnter the number of employees: ");
// convert into an integer empcount
int employeeCount = Integer.parseInt(employeeCountString);
// initialize the empArray.
Employee2[] empArray = new Employee2[employeeCount];
fill(empArray);
printContents(empArray);
} //end main method
private static void fill(Object[] my_arr) {
int i;
for (i = 0; i < my_arr.length; i = i + 1) {
// get the name from the keyboard
String employeeName = JOptionPane.showInputDialog(
"Enter the employee name: ");
// do something here to set the array element to employeeName
// get the salary
String employeeSalaryString = JOptionPane.showInputDialog(
"Enter the employee monthly salary: ");
//convert into a double
double employeeSalary = Double.parseDouble(employeeSalaryString);
//do something here to set array for salary
my_arr[i] = new Employee2(1,"S1",5); // temporary values here
} //ends for loop
} // ends method
private static void printContents(Object[] the_arr) {
int i;
for (i = 0; i < the_arr.length; i = i + 1) {
System.out.print("Element: " + i);
//System.out.println(" has the value : " + the_arr);
System.out.println(" has the value : " + i);
} //ends for loop
} // ends printContents method
} // ends EmpTest classwhat's the matter ?
Try this :
import javax.swing.JOptionPane;
public class EmpTest {
public static void main(String[] args_) {
// Create object based on EmployeeTest2 class
// to add employee data to the array called empArray
Emp emp1 = new Emp(1, "Smith", 2000);
Emp emp2 = new Emp(2, "Jones", 2500);
// test and confirm the objects emp1 and emp2
int i;
String n;
double s;
double newsal;
// get the salary after the 5 percent raise
i = emp1.getID();
n = emp1.getName();
s = emp1.getSalary();
newsal = emp1.raise();
System.out.println("object Employee 1 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: "
+ newsal);
i = emp2.getID();
n = emp2.getName();
s = emp2.getSalary();
newsal = emp2.raise();
System.out.println("object Employee 2 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: "
+ newsal);
// get the number of employees with JOptionPane
String employeeCountString = JOptionPane.showInputDialog("Employee Database "
+ "\nEnter the number of employees: ");
// convert into an integer empcount
int employeeCount = Integer.parseInt(employeeCountString);
// initialize the empArray.
Emp[] empArray = new Emp[employeeCount];
fill(empArray);
printContents(empArray);
} // end main method
private static void fill(Object[] my_arr) {
int i;
for (i = 0; i < my_arr.length; i = i + 1) {
// get the name from the keyboard
String employeeName = JOptionPane.showInputDialog("Enter the employee name: ");
// do something here to set the array element to employeeName
// get the salary
String employeeSalaryString = JOptionPane.showInputDialog("Enter the employee monthly salary: ");
// convert into a double
double employeeSalary = Double.parseDouble(employeeSalaryString);
// do something here to set array for salary
my_arr[i] = new Emp(1, employeeName, employeeSalary); // temporary values here
} // ends for loop
} // ends method
private static void printContents(Object[] the_arr) {
int i;
for (i = 0; i < the_arr.length; i++) {
System.out.print("Element # "+i+" Name= "+ ((Emp)the_arr).getName());
System.out.print("Salary # "+i+" Salary = "+ ((Emp)the_arr[i]).getSalary());
} // ends for loop
} // ends printContents method
} // ends EmpTest class -
How to export and import customized Object
Hi All,
I would like to communicate with system clipboard by importing and exporting the Objects.
Assume that i have a RectangleBean object containing x,y,width and height properties and respective setters and getters.
i am drawing the rectangle object by using the RectangleBean object values.
now i want to export and import the RectangleBean object to system clipbord to draw a rectangle on other window when the user performed paste functionality. In other words communicating the RectangleBean objects between the two windows.
Thanks in Advance
Dorairaj MDoraiRaj wrote:
Hi All,
I would like to communicate with system clipboard by importing and exporting the Objects.
Assume that i have a RectangleBean object containing x,y,width and height properties and respective setters and getters.
i am drawing the rectangle object by using the RectangleBean object values.
now i want to export and import the RectangleBean object to system clipbord to draw a rectangle on other window when the user performed paste functionality. That's not going to work: if you are talking past the bean object into the clipboard and have something like MS-Word use it as a way of recreating your graphic using your bean... no, that's just not going to happen.
If you are saying you want to create another of your graphics on another Java window in the same JVM session, then just pass a reference of the window's graphic context to a setter and have at it.
If you're talking about some JEE functionality, then you're going to have to use RMI or some other standard method to get your object over to the other box or it's effects.
In other words communicating the RectangleBean objects between the two windows.Not by cutting and pasting to the clipboard. -
Have trouble with CMP and relationships
Hello and Thank you for your time.
I'm having a bit of trouble using entity beans and CMP, I'm probably doing some thing wrong. The main problem I am having is with a many to many relationship. Let's say I have the following code:
ClassA.java
@Entity
public class ClassA implements Serializable {
<other variables>
private Collection<Class1> class1Collection;
<other methods>
@ManyToMany(cascade=CascadeType.ALL, mappedBy = "classACollection")
public Collection<Class1> getClass1Collection() {
return class1Collection;
public void setClass1Collection(Collection<Class1> class1Collection) {
this.class1Collection = class1Collection;
Class1.java
@Entity
public class Class1 implements Serializable {
<other variables>
private Collection<ClassA> classACollection;
<other methods>
@ManyToMany
public Collection<ClassA> getClassACollection() {
return class1Collection;
public void setClassACollection(Collection<ClassA> classACollection) {
this.class1Collection = class1Collection;
In the 'other variables' each table has a @Id field and setters and getters for the Id.
This code half works. If I set the collection in ClassA with a Collection of Class1 objects this is populated in to the database and the getClass1Collection method for this also works. If I then try to use the getClassACollection method from a Class1 object the entity manager throws a relationship not complete exception (or some thing to that effect). it is also the case that if I create a list of ClassA objects and place it in to the Class1 objects variable, this does not populate in to the database.
Some thing similar also happens with OneToMany and ManyToOne relationship (only one side of the relationship seems to be part of the relationship)
What am I doing wrong?
Edited by: tehBoris on Mar 26, 2010 1:18 PMYes, that's as it should be, but I think the problem is the default for adding the auto page numbers. The default on the top of the dialog box that appears when you choose Auto Page Numbers from the menu says:
Show in Document.
That seems to be the default. Page numbers in sections won't work with that default. To get it to work, you have to select:
Show in Current Section.
I think I'm right on this, but I'm not sure. I'll have to practice some more. Perhaps this is a default that should be changed in the next version, but I don't know.
Tom
Maybe you are looking for
-
Can't see files while updating to FileVault 2?
Hi, I have an older version of the Macbook Pro and have recently upgraded my system from Mavericks to Yosemite. Today I upgraded from Legacy FileVault to the newer FileVault, and I had followed all the instructions given by Apple. However, right now
-
Thanks for the info, Kyle. I will probably try to find an older 32-bit XP machine. VM is just not an option for me right now.
-
I am suddenly no longer able to pick up wifi...Please help!
Ever since I added a 4th gen ipod to my family, my 2nd gen ipod no longer picks up the wifi signal in my house. It wont pick up any wifi signal on my street where as the other ipod, as well as my cell and laptop pick up 5 or 6 networks! I had an ap
-
I've tried deleting Firefox and reinstalling it and I still can't open up Firefox. How can I fix this?
-
How do i send data to a servlet through a hyperlink?
i have /Servlet?id=1 is that the way to do it...? please help.. i want the id to be sent to the servlet... the url mapping works fine but i keep getting null values......when reaching the final page... thanks