3

I have been struggling with setters and getters in java for quite a long time now.

For instance, if I want to write a class with some information as name, sex, age etc with appropriate set and get methods. Then in a another class I want to test my set and getters with this as a example:

personInfo = myInfo() = new Personinfo("Anna", "female", "17");

How do I do that?

I know that I can have a printout like:

public void printout() {
    System.out.printf("Your name is:  " + getName() + 
              " and you are a " + getSex());
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Eri.
  • 465
  • 2
  • 6
  • 14

7 Answers7

2

This is a simple example to show you how to do it:

public class Person {
private String name;
private String gender;
private int age;
Person(String name, String gender, int age){
    this.name = name;
    this.gender = gender;
    this.age = age;
}
public void setName(String name){
    this.name = name;
}
public void setGender(String gender){
    this.gender = gender;
}
public void setAge(int age){
    this.age = age;
}
public String getName(){
    return this.name;
}
public String getGender(){
    return this.gender;
}
public int getAge(){
   return this.age;
}
public static void main(String[] args)
{
    Person me = new Person("MyName","male",20);
    System.out.println("My name is:" + me.getName());
    me.setName("OtherName");
    System.out.println("My name is:" + me.getName());
}
}

This will print out:

My name is:MyName

My name is:OtherName

sergiuprdn
  • 61
  • 4
  • The default constructor is a constructor which is automatically generated by the compiler unless you define another constructor. So in this case the default constructor will not be generated, because i explicitly defined a constructor with 3 arguments. – sergiuprdn Jul 08 '13 at 16:21
  • Is there any difference of returning with the this keyword or can I simply just return just for example? Instead of return this.age; just return age; – Eri. Jul 08 '13 at 21:11
  • In this case it would work only by using return age, but if a variable would be defined in the method with the same name as the instance variable then we would need to make a difference between the two using the keyword this. – sergiuprdn Jul 09 '13 at 06:56
1

You need to create an object of one class in the other class. You can then call the .get() and .set() methods on them. I will post an example in 2 minutes

First class (i'll call it Person) will have methods to return its fields

private String name = "";
private String age = 0;

public Person(String name, int age) {
  this.name = name;
  this.age = age;
}

public String getName() {
  return name;
}

public int getAge() {
  return age;
}

The second class will call those methods after it creates an object of the first class

bob = new Person("Bob", 21);
System.out.println("Your name is: " +  bob.getName() + 
                    " and you are " +  bob.getAge());
Stephan
  • 16,509
  • 7
  • 35
  • 61
  • Also I fixed your print statement syntax in your question to use println (easier for beginners) and fixed a concatenation error – Stephan Jul 08 '13 at 14:45
  • 1
    you will have to declare name and age as private, else i don't see much use of restricting to getter, setters – Space Rocker Jul 08 '13 at 14:55
  • You need to declare the getName and getAge access modifiers. I think protected is the default. public is probably what's desired. – William Morrison Jul 08 '13 at 14:57
  • @SpaceRocker no real need, but I did it anyway for good practice I guess. getters and setters are usually waste of time for a program this simple, the point is to teach how they are used – Stephan Jul 08 '13 at 14:59
  • And also, is it OK to do like this in the name setter? if (name == anna) { this.name = "name taken"; } else { this.age = age; } – Eri. Jul 08 '13 at 21:21
  • yes, you can make a setter for age just like this @Erica you will need to make it public, and the method will need to have an int argument – Stephan Jul 08 '13 at 21:22
  • If I try to change something with the setter I still receive the same value as I send, for instance if I make an if statement (that shall change Eric to Stephan) in a setter and with it change this.name = "Stephan" it will not be changed when I call getName(). It will still return Eric. – Eri. Jul 08 '13 at 21:24
  • A better example: `code public void setAge(int age){ if (age == 20) { this.age = 1337; } else { this.age = age; } } ` – Eri. Jul 08 '13 at 21:31
  • So in this case even if I send age 20 and later call getAge() it will stil return 20 instead of 1337. And btw, many thanks so far for helping me, I know I might be very bad and hard to understand. Sorry for that! – Eri. Jul 08 '13 at 21:33
  • @Erica if you use the setter to change eric to stephan, then when you use the getter, it will give you stephan, not eric – Stephan Jul 08 '13 at 22:09
  • @Erica no problem i enjoy helping – Stephan Jul 08 '13 at 22:09
  • I use the getter but it is not changing anything. – Eri. Jul 09 '13 at 12:21
  • `code public void setGender(String gender){ if (gender == "male") { this.gender = "man"; }` – Eri. Jul 09 '13 at 12:21
  • When I send male and print out getGender() it is not changing it. – Eri. Jul 09 '13 at 12:23
  • @Erica I'd have to see more code, maybe post another question? this one is wiki'd – Stephan Jul 09 '13 at 17:17
  • @Erica you want to use string.equals() instead of "blah" == "blah" – Stephan Jul 09 '13 at 17:55
1

Let eclipse handler it for you

Click on your variable Source > Generate Setter / Getter

Maulzey
  • 4,100
  • 5
  • 22
  • 30
  • 7
    Although I agree, it looks like this person does not understand the basics of the language. Getting a tool to create code which he doesn't understand (especially at this level) is a bad idea. – Jon Taylor Jul 08 '13 at 14:43
  • Yes I need to learn from the scratch before I start to generate code, but thanks for the tip. I will keep it in mind. – Eri. Jul 08 '13 at 14:48
  • To read it right, refer 'Head first java' Chapter 4, topic Getter and Setter – Maulzey Jul 08 '13 at 18:18
1

The point of getters and setters is to let you limit/expand the scope or functionality of your property, independent of each other.


You may want your 'name' property to be readonly outside of your PersonInfo class. In this case, you have a getter, but no setter. You can pass in the value for the readonly properties through the constructor, and retrieve that value through a getter:

public class PersonInfo
{
    //Your constructor - this can take the initial values for your properties
    public PersonInfo(String Name)
    {
        this.name = Name;
    }

    //Your base property that the getters and setters use to 
    private String name;

    //The getter - it's just a regular method that returns the private property
    public String getName()
    {
        return name; 
    }
}

We can use getName() to get the value of 'name' outside of this class instance, but since the name property is private, we can't access and set it from the outside. And because there is no setter, there's no way we can change this value either, making it readonly.


As another example, we may want to do some validation logic before modifying internal values. This can be done in the setter, and is another way getters and setters can come in handy:

public class PersonInfo
{
    public PersonInfo(String Name)
    {
        this.setName(Name);
    }

    //Your setter
    public void setName(String newValue)
    { 
        if (newValue.length() > 10)
        {
            this.name = newValue;
        }
    }

Now we can only set the value of 'name' if the length of the value we want to set is greater than 10. This is just a very basic example, you'd probably want error handling in there in case someone goes jamming invalid values in your method and complains when it doesn't work.


You can follow the same process for all the values you want, and add them to the constructor so you can set them initially. As for actually using this pattern, you can do something like the following to see it in action:

public static void main(String[] args)
{
    PersonInfo myInfo = new PersonInfo("Slippery Sid",97,"male-ish");
    var name = myInfo.getName();
    System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());

    myInfo.setName("Andy Schmuck");
    System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
}
Ashley
  • 35
  • 5
0

You create an object by instantiating the constructor as follows

Personinfo pi = new Personinfo("Anna", "female", "17");

You can then call methods upon that object as follows

pi.setName("Alan");

or

pi.getName();
Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
0

In personInfo:

public Person(String n, int a, String s){
    this.name=n;
    this.age=a;
    this.sex=s;
}
public String getName(){
   return this.name;
}
public int getAge(){
   return this.age;
}
public String getSex(){
   return this.sex;
}
public void setName(String n){
   this.name = n;
 }
 public void setAge(int a){
   this.age = a;
 }
 public void setSex(String s){
   this.sex = s;
 }

Then fix the print statement:

System.out.println("Your name is: " + myInfo.getName() + " and you are a " +        myInfo.getSex());
Marco Corona
  • 812
  • 6
  • 12
0

here's how you do it:

public class PersonInfo {

    private String name;
    private String sex;
    private int age;


    /** GETTERS **/

    public String getName(){
        return name;
    }

    public String getSex(){
        return sex;
    }

    public int getAge(){
        return age;
    }

    /** SETTERS **/

    public void setName(String name){
        this.name = name;
    }

    public void setSex(String sex){
        this.sex = sex;
    }

    public void setAge(int age){
        this.age = age;
    }
}

class Test{
    public static void main(String[] args){
        PersonInfo pinfo = new PersonInfo();
        pinfo.setName("Johny");
        pinfo.setSex("male");
        pinfo.setAge(23);

        //now print it

        System.out.println("Name: " + pinfo.getName());
        System.out.println("Sex: " + pinfo.getSex());
        System.out.println("Age: " + pinfo.getAge());

    }
}

Or you can add this as well:

@Override
public String toString(){
    return "Name: " + this.name + "\n" +
            "Sex: " + this.sex + "\n" +
            "Age: " + this.age;
}

and then just to a .toString

EDIT:

Add this constructor in the class to initialize the object as well:

public PersonInfo(String name, String sex, int age){
    this.name = name;
    this.sex = sex;
    this.age = age;
}
Space Rocker
  • 787
  • 3
  • 11
  • 25
  • This seems to be it, I know this! But now, in my other class, how do I pass information to them? I know it can look like this: personInfo = myInfo() = new Personinfo("Anna", "female", "17"); for example. – Eri. Jul 08 '13 at 14:50
  • well just add constructor in the above class, – Space Rocker Jul 08 '13 at 14:52
  • This is something I don't get. Why then have setters and getters when I have to initialize them with a constructor? – Eri. Jul 08 '13 at 14:56
  • you don't, since you put up example that you want it this way so that's a possibility but you don't do it in practice. – Space Rocker Jul 08 '13 at 14:58
  • and sometimes, you have some mandatory variables that are must to be set, while some are optional, so you can combine such a way that put the mandatory ones in constructor while optional ones (sometimes set with default value) as setters – Space Rocker Jul 08 '13 at 14:59