Get and set examples in java

Get and set examples in java

Вопрос, почему мы не задаем в конструкторе класса значение через сеттер (в котором выполнена проверка на валидность), а задаем что-то типа this.value = value (вместо setValue(value)) ?? Ниже написал код в виде примера. Если бы в конструкторе было this.value = value, то при инициализации объекта значением например -3 в конструкторе всё было бы ОК. А сеттер в конструкторе не даст сделать такой глупости.

 public class Main < public static void main(String[] args) < //это значение не вызовет ошибку, пока оно положительное: MyClass myClass = new MyClass(3); //MyClass myClass = new MyClass(-3) //тут будет ошибка! myClass.setValue(4); //это значение не вызовет ошибку //myClass.setValue(-4); //а это вызовет ошибку! System.out.println(myClass.getValue()); >> class MyClass < private int value; public MyClass(int value) < setValue(value); >public int getValue() < return value; >public void setValue(int value) < if (value < 0) < throw new IllegalArgumentException ("Значение value должно быть положительным числом!"); >this.value = value; > > 

Для быстрого создания getter и setter в IntelliJ IDEA выделяете переменную класса и нажимаете alt + insert, во всплывшем окошке можно выбрать что хотите создать.

Интересно, почему в гетере пишут просто return name а можно написать так public String getName() < return this.name; >потому что так просто короче? Или функционал меняется?

Что-то я не совсем понял, даже если я объявил переменную класса private но создал сеттер, то мой объект извне можно все равно изменять, разница лишь в проверке значений. А если я не хочу чтобы мой объект изменяли, то я просто не пишу сеттер? Но смогу ли я сам менять значения объекта?

в конструкторе ведь то же можно указать ограничения при создании объекта?,и еще вопрос в Idea можно изменить название переменной сделав пару кликов,и оно меняется везде в коде вот эта замена это аналог замены через сеттер без потери потерь или там более простая логика и он тупо меняет названия?

А если я при создании объекта передам не корректные значения? Cat barsik = new Cat(«noname», -1000, 1000); Надо ли делать валидацию в конструкторе?

Источник

Java Encapsulation

You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set , followed by the name of the variable, with the first letter in upper case:

Читайте также:  Генератор случайных кодов html

Example

public class Person < private String name; // private = restricted access // Getter public String getName() < return name; >// Setter public void setName(String newName) < this.name = newName; >> 

Example explained

The get method returns the value of the variable name .

The set method takes a parameter ( newName ) and assigns it to the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private , we cannot access it from outside this class:

Example

If the variable was declared as public , we would expect the following output:

However, as we try to access a private variable, we get an error:

MyClass.java:4: error: name has private access in Person
myObj.name = «John»;
^
MyClass.java:5: error: name has private access in Person
System.out.println(myObj.name);
^
2 errors

Instead, we use the getName() and setName() methods to access and update the variable:

Example

public class Main < public static void main(String[] args) < Person myObj = new Person(); myObj.setName("John"); // Set the value of the name variable to "John" System.out.println(myObj.getName()); >> // Outputs "John" 

Why Encapsulation?

  • Better control of class attributes and methods
  • Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Flexible: the programmer can change one part of the code without affecting other parts
  • Increased security of data

Источник

What is the use of get and set in java.And where should it be used?

I am a beginner in Java.I recently came across it in java.I am trying to making a login form and I am trying to use get and set for it.I have classes for username And password verification I also have a registration class to register the user. In which classes and how should I use get and set?

Before learning any OOP language, OOPS concept should be clear. For this getter setter problem this link could be useful for you:-stackoverflow.com/questions/8830772/…

3 Answers 3

GET and SET are methods that can be invoked by an object the set prefix is usually used in methods that set a value to an object’s attribute and the get method does the opposite of that it gets the value of the attribute that you have set on the object.

Can you please tell the advantages of get and set over normal methods for passing a variable to a class.

well there are methods that uses an entire object as a parameter for example a class User that has a username and password attribute can be passed on the loginAuthentication(User objectName) method which has a User class parameter. and it would be more convenient the more parameters that needs to be passed, the GET and SET method are one of the many good coding techniques of OOP(object oriented programming) that makes it easier for other people or yourself to maintain and understand your code’s flow.

Читайте также:  Как установить sqlite python

getter and setter methods in Java help you achieve Encapsulation which is fundamental concept of Object Oriented programming. You can achieve this by declaring private data members while making setter and getter methods public.
In a login form, you have username and password. You will pass them to java class where you can set/get the value of these data members for the current value being passed. For Example,

class Login < private String username; private String password; public void setUsername(String username)< this.username = username; >public String getUsername() < return username; >public void setPassword(String password) < this.password= password; >public String getPassword() < return password; >> 

In your validation LoginForm validation class, you can use the setter and getter method instead of getting the values from the request parameter for example as req.getParameter(«username»). Not only in your validate class but also, when ever you need to change or get username and password parameters, you can use getter and setter methods.

Источник

What are the Get and Set Methods in Java

In Java programming, there can often be a requirement for the developer to utilize the implemented code differently. For instance, passing multiple values to a particular variable from time to time as per requirement. In such cases, Java’s “get” and “set” methods help manage the memory and simplify the code effectively.

This blog will state the usage and implementation of Java’s “get” and “set” methods.

What are the “get” and “set” Methods in Java?

The “get” method is used to return the value of the private variable, and the “set” method sets/allocates the value of the private variable. These methods are a part of the “encapsulation” process in which the sensitive data is hidden from the users.

Example 1: Getting and Setting Values in Java

In this example, the “set()” and “get()” methods functionality can be utilized first to set the value of the private variable and then fetch it with the help of the user-defined functions within the class:

public void setAge ( int x ) {

public static void main ( String [ ] args ) {

getandset x = new getandset ( ) ;

System . out . println ( «The age is: » + x. getAge ( ) ) ;

  • Firstly, define a class named “getandset”.
  • Within the class, specify a private variable named “age”.
  • In the next step, define a function named “setAge()” having the stated parameter to set the value. In the function definition, pass the set value to the private variable.
  • Now, declare a function for fetching the set value named “getAge()”. In its definition, simply return the “set” age.
  • In the “main”, create an object of the declared class via the “new” keyword and the “getandset()” constructor, respectively.
  • After that, invoke the accumulated function “setAge()” by referring to the class and setting the specified value.
  • Lastly, retrieve the set value by accessing the latter class function “getAge()”.
Читайте также:  Create threads in python

In this output, it can be observed that the set value is retrieved appropriately.

Example 2: Getting and Setting Values by Reference in Java

In this particular example, the values can be set and get by referring to the private variable:

public void setAge ( int age ) {

public static void main ( String [ ] args ) {

getandset x = new getandset ( ) ;

System . out . println ( «The age is: » + x. getAge ( ) ) ;

In the above lines of code, apply the following steps:

  • Likewise, define a class named “getandset” and specify the stated private variable.
  • Now, define a function named “setAge()” having the parameter “age” to set the value.
  • Note that the parameter and the private variable are identical, so “this” keyword can be utilized here to omit the ambiguity in differentiation.
  • The “this” keyword points to the private variable and allocates it the set value after passing it as a function argument in the main.
  • After that, similarly, define the function “getAge()” to return the set value.
  • In the “main”, recall the discussed approaches to create a class object, set, and get the value accordingly.

In this outcome, it can be analyzed that the ambiguity between the identical values is sorted out by passing reference.

Conclusion

The “get” and “set” methods in Java are a part of “encapsulation” and are used to return and set the value of the private variable, respectively. These methods can be used to modify the variable simply or by passing the reference with the help of the user-defined function. This blog discussed the approaches to utilizing Java’s get and set methods.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

Источник

Оцените статью