Setter getter ..? what is this and what it does ?
i searched over google but didn't find the suitable answer...!

Recommended Answers

All 23 Replies

Hello,

The name pretty much implies what it is, getter methods get variables, and setter methods set variables.

Say for instance you a have a class called Contact, the "getName()" method in the Contact class would return the Name variable.

Like so:

public class Contact
{
	String firstName,

	public Contact(String firstName)
	{
		this.firstName = firstName;
	}
	
	public String getfirstName()
	{
		return firstName;
	}
}

Setter methods then would set the Name variable, so you would invoke the "setName()" method of the Contact class like e.g Contact.setName("Xufyan"); And then the Name variable in the Contact class will be set to "Xufyan"..

So then this would be the code in your Contact class for the setter method:

public void setfirstName(String firstName)
	{
		this.firstName = firstName;
	}

Hope this helped!

commented: nice +0

Why do we have to use setter if we can use a parametrized constructor to set the name ??
and how do we set the name using setter, should i have to create an object before setting up the name ??
See this,

class Contact{
	String firstName;

	public Contact(String firstName){
		this.firstName = firstName;
	}
	
	public String getfirstName(){
		return firstName;
	}
	
	public void setfirstName(String firstName){
		this.firstName = firstName;
	}
}
class setter1{
public static void main(String args[]){
Contact contact1 = new Contact("Xufyan"); // name is set using parametrized constructors
	}
}

now how to use setter to set the name in above program??
Why you've created a parametrized constructor if you want to set the name using setter ?
if we can use parametrized constructor then why do we have to use setter/getter ?

The purpose of getters & setters is to hide the implementation of a datatype from the "user" (usually another programmer). If I write a class, I usually need a way to allow you to set up the data the way you want, but I don't necessarily want you to know about the datatypes I'm using to store your data. So I give you get & set methods.

There are arguments about setters though, and you have uncovered one reason why some people say you should not provide setters, only getters. As your argument suggests, you should create a constructor that takes whatever parameters are needed for a correctly fully formed object, and then there would be no need for setters. But not all classes are coded that way.

For example, the Rectangle class in Java has a constructor with no parameters. It creates a rectangle whose upper-left corner is at (0, 0) and whose width and height are both zero. Then you can call setSize() later on the object if you want.

When you create a class, you have to think about how it will be constructed and used, and how much flexibility you want to provide to the user of your class, understanding that you might have to write more error-checking code if you allow a user to construct an object that's not "fully formed".

The purpose of getters & setters is to hide the implementation of a datatype from the "user" (usually another programmer). If I write a class, I usually need a way to allow you to set up the data the way you want, but I don't necessarily want you to know about the datatypes I'm using to store your data. So I give you get & set methods.

There are arguments about setters though, and you have uncovered one reason why some people say you should not provide setters, only getters. As your argument suggests, you should create a constructor that takes whatever parameters are needed for a correctly fully formed object, and then there would be no need for setters. But not all classes are coded that way.

For example, the Rectangle class in Java has a constructor with no parameters. It creates a rectangle whose upper-left corner is at (0, 0) and whose width and height are both zero. Then you can call setSize() later on the object if you want.

When you create a class, you have to think about how it will be constructed and used, and how much flexibility you want to provide to the user of your class, understanding that you might have to write more error-checking code if you allow a user to construct an object that's not "fully formed".

Ok i understand why do we use setter , but you didn't answer my other questions

i searched over google but didn't find the suitable answer...!

The technical OO terminology is "accessors and mutators" - googling these will give you lots of good info.

Here's a good article to start with:

http://java.about.com/od/workingwithobjects/a/accessormutator.htm

commented: thanks - i didn't knew about accessors and mutators ! :D +0

Yes, you have to create an object first, before calling getters and setters.

class setter1{
   public static void main(String args[]){
      Contact contact1 = new Contact("Xufyan");
      // do some other stuff
      contact1.setName("John");  // example of calling setter
      // do some other stuff
      String name = contact1.getName();  // example of calling getter
   }
}

Note that even if you have a parameterized constructor, you still want to provide getters since the user may need to "read" the info in the object, even if s/he can't "write" new info with a setter.

Hope that helps.

Yes, you have to create an object first, before calling getters and setters.

class setter1{
   public static void main(String args[]){
      Contact contact1 = new Contact("Xufyan");
      // do some other stuff
      contact1.setName("John");  // example of calling setter
      // do some other stuff
      String name = contact1.getName();  // example of calling getter
   }
}

Note that even if you have a parameterized constructor, you still want to provide getters since the user may need to "read" the info in the object, even if s/he can't "write" new info with a setter.

Hope that helps.

why you have over written the name ???
first you set the name to Xufyan , then you overwrite it with John ???
How it can be benifical can you give an example ?

Name isn't a very realistic example, but how about:
Bank account - interest rate is set when account is created, but may be changed at any time later
Product in shop - price ditto

can you give example with the code ?>?

You already have samples of code, just use your own imagination to apply them to the other examples.

What should i've to do if i want to create one get and one set method for more than one values ???
Example:

String Name;
int Age;

how could i create a single getter and setter for these two ?

A method can have any number of parameters, so you can set any number of things in one setter eg

person.setEmployment(String employer, float salary);

A method can only return one value, so you cannot return name and age from one getter.
When you have two or more values that need to be kept together like this you can consider making a simple class that has those 2+ values as its instance variables. That way you can get syntax like:

Employment e = person.getEmployment();
System.out.println(e.getName() + e.getSalary());

A method can have any number of parameters, so you can set any number of things in one setter eg

person.setEmployment(String employer, float salary);

A method can only return one value, so you cannot return name and age from one getter.
When you have two or more values that need to be kept together like this you can consider making a simple class that has those 2+ values as its instance variables. That way you can get syntax like:

Employment e = person.getEmployment();
System.out.println(e.getName() + e.getSalary());

oki understand how to set the values but i didn't understand how to return those values using get from one setter ?

how could i create a single getter and setter for these two ?

You typically don't; if you did, it really wouldn't be called a "getter" or "setter" in normal Java sense.

Also, if you did that, you would be making assumptions about the problem domain being modeled. In such cases, you create other methods which suit the job at hand and have those methods in your business classes. Keeping your getter and setters for value objects *dumb* would help you in the long run.

See this example,

class Student{
	int rollno;
	String name;
	
	public void setValues (int rollno, String name){
	this.rollno = rollno;
	this.name = name;
	}
	
	public Student getValues(){
	Student s = new Student();
	s.rollno=this.rollno;
	s.name=this.name;
	return s;
	}
}

class TestSTD{
public static void main(String args[]){
	Student s1 = new Student ();
	s1.setValues(40, "Sufyan");
	Student s2 = new Student ();
	s2.setValues(30, "Ghori");
	Student s3 = new Student ();
	s3 = s2.getValues();
	System.out.print (s3.name + " " + s3.rollno);
	
 }
}

in this example i've created two instance variable rollno and name
then i created a setter to set the values OK ?

but i didn't understand this,

public Student getValues(){ // What is mean by this line ?
	Student s = new Student(); // object in the same class ? :confused:
	s.rollno=this.rollno;
	s.name=this.name;
	return s;
	}

and this, s3 = s2.getValues(); // How getValues is called there ! ?

Actually this has been taught by my teacher in university but i missed that class so i am not able to understand this..!

That's an example of what I just said. The get method returns rollno and name by putting them into a new class and returning that class contining both values.

public Student getValues(){

The line above is the declaration of a public function called getValues which takes no arguments and returns an object of type Student.

Student s = new Student(); // object in the same class ? :confused:

The line above creates a local object variable called s of type Student inside the function. The purpose of creating this variable is so its member variables can be set and then the object is returned from the function.

s3 = s2.getValues(); // How getValues is called there ! ?

The line above refers to 2 different Student objects. One is called s2 and one is called s3. The getValues function is called on the s2 object, and the Student object returned from that function is assigned to the variable s3. So after the function call, s2 and s3 both have rollno=30 and name=Ghori, although they are different Student objects in memory.

commented: you're rocking ! +0

That's an example of what I just said. The get method returns rollno and name by putting them into a new class and returning that class contining both values.

can you please exlain this, ?
why uses the class name in the method?? public Student getValues(){

public Student getValues(){

The line above is the declaration of a public function called getValues which takes no arguments and returns an object of type Student.

Student s = new Student(); // object in the same class ? :confused:

The line above creates a local object variable called s of type Student inside the function. The purpose of creating this variable is so its member variables can be set and then the object is returned from the function.

s3 = s2.getValues(); // How getValues is called there ! ?

The line above refers to 2 different Student objects. One is called s2 and one is called s3. The getValues function is called on the s2 object, and the Student object returned from that function is assigned to the variable s3. So after the function call, s2 and s3 both have rollno=30 and name=Ghori, although they are different Student objects in memory.

public Student getValues(){

Why you are calling it a function ???? is it a function or a method?

In java they are all methods. A method that returns a value based (only) on its parameters can also be called a function. In practice many people use these terms casually. You can treat them as being the same unless you want to get very technical about programming theory.

getter and setter methods are specifications of Java MDB standards. The instance varibales are private. So to change their values and retreive their values we specify getter and setter methods.

The setter and getter methods are the accessor and mutator method which is usually used in the java beans to provide the security to the method in a class.


1) By doing this we can access the varible of an class dynamically and can set the variable dyanmically.

2)It is generally used in the purpose of 3-tier architecture eg:-sql,java,jsp,html

3)see the mvc architecture u get a clear idea of it
mvc(model,view,controller).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.