Install and get methods in java?

How can I use the set and get methods, and why should I use them? Are they really helpful? And can you also give examples of the set and get methods?

+45
java methods encapsulation setter getter
Jul 10 '11 at 3:20
source share
15 answers

The Set and Get methods are an example of data encapsulation. Instead of directly accessing class member variables, you define get methods to access these variables and set methods to change them. By encapsulating them in this way, you control the open interface if you need to change the inner workings of this class in the future.

For example, for a member variable:

 Integer x; 

You may have methods:

 Integer getX(){ return x; } void setX(Integer x){ this.x = x; } 



chiccodoro also mentioned an important point. If you want to allow read access to the field for any foreign classes, you can do this by providing only the public get method and keeping set private or not providing set at all.

+51
Jul 10 '11 at 3:24
source share

I want to add to other answers that installers can be used to prevent an object from being placed in an invalid state.

For example, suppose I have to set TaxId modeled as String. The first version of the installer may be as follows:

 private String taxId; public void setTaxId(String taxId) { this.taxId = taxId; } 

However, we better prevent the use of an object with an invalid taxId, so we can enter a check:

 private String taxId; public void setTaxId(String taxId) throws IllegalArgumentException { if (isTaxIdValid(taxId)) { throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid"); } this.taxId = taxId; } 

The next step to improve the modularity of the program is to make TaxId itself as an object that can test itself.

 private final TaxId taxId = new TaxId() public void setTaxId(String taxIdString) throws IllegalArgumentException { taxId.set(taxIdString); //will throw exception if not valid } 

Similarly for getter, what if we don't have a value yet? Perhaps we want to have a different path, we could say:

 public String getTaxId() throws IllegalStateException { return taxId.get(); //will throw exception if not set } 
+21
Jul 10 2018-11-11T00:
source share

I think you need something like this:

 public class Person { private int age; //public method to get the age variable public int getAge(){ return this.age } //public method to set the age variable public void setAge(int age){ this.age = age; } } 

You simply call such a method on an instance of the object. Such methods are useful, especially if installing something should have side effects. For example. if you want to respond to certain events, for example:

  public void setAge(int age){ this.age = age; double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age; if(averageCigarettesPerYear >= 7300.0) { this.eventBus.fire(new PersonSmokesTooMuchEvent(this)); } } 

Of course, this can be dangerous if someone forgets to call setAge(int) , where he should, and sets age directly using this.age .

+7
Apr 29 '14 at 12:25
source share

To access fields, it is preferable to use access methods, since it controls access to fields (it can impose data validation, etc.) and is suitable for interfaces (interfaces cannot require fields, only methods).

+6
Jul 10 '11 at 3:24
source share

Setters and receivers are used to replace direct access to member variables from external classes. if you use setter and getter to access a property, you can enable initialization, error checking, complex conversions, etc. Some examples:

 private String x; public void setX(String newX) { if (newX == null) { x = ""; } else { x = newX; } } public String getX() { if (x == null) { return ""; } else { return x; } } 
+5
Jul 10 '11 at 3:25
source share

Some advantages of using getters and setters (known as encapsulation or data-hiding ):

(originally answered here )

1. Class fields can be made read-only (providing getter only) or write-only (by providing only setter). This gives the class full control over who gets access to / change their fields.

Example:

 class EncapsulationExample { private int readOnly = -1; // this value can only be read, not altered private int writeOnly = 0; // this value can only be changed, not viewed public int getReadOnly() { return readOnly; } public int setWriteOnly(int w) { writeOnly = w; } } 

2. Class users do not need to know how the class actually stores data. This means that data is shared and independent of users, which makes it easier to modify and maintain code. This allows maintainers to make frequent changes, such as bug fixes, design and performance improvements, without affecting users.

In addition, encapsulated resources are equally accessible to each user and have identical behavior, not dependent on the user, since this behavior is internally defined in the class.

Example (getting value):

 class EncapsulationExample { private int value; public int getValue() { return value; // return the value } } 

Now, what if I want to return the value twice? I can just change my getter, and all the code that uses my example does not need to be changed and will get twice as much value:

 class EncapsulationExample { private int value; public int getValue() { return value*2; // return twice the value } } 

3. Makes the code cleaner more understandable and understandable.

Here is an example:

No encapsulation:

 class Box { int widthS; // width of the side int widthT; // width of the top // other stuff } // ... Box b = new Box(); int w1 = b.widthS; // Hm... what is widthS again? int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here! 

With encapsulation:

 class Box { private int widthS; // width of the side private int widthT; // width of the top public int getSideWidth() { return widthS; } public int getTopWIdth() { return widthT; } // other stuff } // ... Box b = new Box(); int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew! 

See how much more control you have, what information you get and how much clearer it is in the second example. Keep in mind that this example is trivial and in real classes you will have to deal with a lot of resources that are accessed by many different components. Thus, the encapsulation of resources makes it clearer which of them we are referring to and how (getting or setting).

Here is a good SO thread on this topic.

Here's a good read for encapsulating data.

+4
Oct 16 '14 at 2:55
source share

The answers above summarize the role of getters and setters better than I could, however I would like to add that your code should ideally be structured to reduce the use of pure getters and setters, i.e. those that do not have complex constructions, validation and and et cetera, as they destroy encapsulation. This does not mean that you can never use them (the answer to stivlo shows an example of using getters and setters), just try to minimize how often you use them.

The problem is that getters and setters can act as a workaround for direct access to personal data. Private data is called private because it is not intended to be shared with other objects; this meant as a representation of the state of the object. Giving other objects access to the closed fields of the object affects the entire target when it is closed in the first place. In addition, you enter a clutch for each recipient or setter that you write. Consider this, for example:

 private String foo; public void setFoo(String bar) { this.foo = bar; } 

What happens if you decide somewhere along the way that you no longer need foo, or want to make it whole? Every object that uses the setFoo method now needs to be changed with foo.

+2
Jul 09 2018-11-22T00:
source share

just because the OOP rule is: Hiding and encapsulating data. It is very bad when to declare an object public and change it on the fly in most situations. There are also many other reasons, but the root is encapsulation in OOP. and “buy a book or read about object-oriented programming”, you will understand all this after you read some book about OOP.

+2
Jul 10 2018-11-11T00:
source share

The benefits of the get () set () methods are as follows.

  • You can easily serialize an object.
  • You can create a permanent object from the containing class.
  • You can easily convert properties to JSON.
  • In a DAO layer (such as Hibernate), you can directly save the object to DB.
  • A simple understanding of an object-oriented concept.
  • Required in all design patterns, with the possible exception of one tone pattern.
  • Security for properties that protect direct access.
  • Polymorphism, encapsulation can be easily understood and implemented by this type of class.

Example:

 private String personName; private int personId; public void setPersonName(String name) throws Exception{ if(!(name.equals("")||name=="")){ this.personName = name; } } public String getPersonName(){ return this.personName; } public void setPersonId(int id) throws Exception{ this.personId = id; } public int getPersonId(){ return this.personId; } 
+1
Jul 10 '11 at 6:20
source share

In the answers, everyone assumes that the object in question is an object with behavior. The best strategy in OOP is to separate data objects (which zip do, have only fields) and behavior objects.

With data objects, it’s great to omit getters and instead have public fields. Usually they do not have setters, since they are most often immutable - their fields are set through constructors and never again. Have a look at Bob Martin's “Clean Code” or “Price and Freeman” A growing OO software ... for details.

+1
Jul 10 '11 at 7:27
source share
 public class Person{ private int age; public int getAge(){ return age; } public void setAge(int age){ this.age = age; } } 

I think you want it .. and it's also called pojo

+1
Apr 29 '14 at 12:28
source share

This answer merges with another question.

Your getAge() method is called an instance method in Java.

To call an instance method, you must have an object of the class in which this method is defined.

For example, if this method is in a class named Person , then

  • Create a Person Object Using the New Operator

      Person p = new Person(); 
  • To get the age of the Person object, use this method

     p.getAge() 
0
Apr 29 '14 at 12:26
source share

this is the code for the set method

 public void setAge(int age){ this.age = age; } 
0
Apr 29 '14 at 12:27
source share

It looks like you are trying to do something similar to C # if you want the createAge method create setAge(int age){ this.age = age;}

0
Apr 29 '14 at 12:28
source share

I do not see a simple answer to the second question (why) here. So here.

Let's say you have a public field that is very often used in your code. Whenever you decide that you need to do something extra before giving or setting this field, you have a problem. You must create a special getter and setter for this field and change your full code using the field directly to use getter and seters.

Now imagine that you are developing a library widely used by many people. When you need to make changes, as described above, and establish direct access to the private field, the code of all people using this field will be broken.

Using getters and seters is the future planning of code, which makes it more flexible. Of course, you can use public fields, especially for simple classes that just contain some data. But it is always useful to simply make the field private and encode the get and set method for it.

0
Aug 26 '14 at 10:58
source share



All Articles