Get and set objects java

Get and Set methods in Java. How do they work?

I’m trying to get a better understanding than I’ve been able to so far. it’s to help me with class, but not with any specific homework assignment; I’m looking for more conceptual information that I’ve not found in my textbook or in the tutorials. On a purely theoretical level, I get why encapsulation is powerful for OO programming, but need a better understanding of what, specifically is going on. I keep confusing myself about the path through which data flows, and wonder where we’re getting and setting data FROM. Hopefully this is not the exception to the «there are no stupid questions» rule. Consider:

 public class Employee < private int empNum; public int getEmpNum() < return empNum; >public void setEmpNum(int Emp) < empNum = emp; >> 

My interpretation of this: Using int Emp passed from somewhere, we set the declared empNum variable in the set. method. We then get. that variable and return it to the calling method. Is that a good understanding? Further Consider:

import.javax.* public class CreateEmp < public static void main(String[] args) < int ssn; ssn = JOptionPane.showInputDialog(null,"enter ssn"); Employee newEmp = new Employee(123456789); JOptionPane.showMessageDialog(null,"Employee ID " + newEmp.getEmpNum); >> 

With this class, I don’t need to explicitly set a variable because declaring new Employee(123456789) automagically sends that value to the set. method. The return in the Employee method returns the resulting value to the calling method and makes that variable available, in this case to my dialog box output. Do I have a handle on that? Here’s where I get confused. With my understanding as noted above—which may be off—I can never decide the best place to put logic. For instance: I would place the «enter employee number» dialog box in the Employee class, with a condition to run ONLY if the parameter passed to the method was null. In my mind, as I understand the data flow, the purpose of the class is to get an employee number. If one is not supplied as a default, one needs to be created. I’m not sure if this thinking is best practices, or if I’m setting myself up for trouble later. I’d love to hear some thoughts about whether or not I’m properly understanding what’s happening.

Читайте также:  Php функции изменения регистра

Источник

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.

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.

Источник

Get and set objects 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 можно изменить название переменной сделав пару кликов,и оно меняется везде в коде вот эта замена это аналог замены через сеттер без потери потерь или там более простая логика и он тупо меняет названия?

Источник

Get and set objects java

Как вы заметили, 2-й элемент массива scores изменяется вне сеттера (в строке 5). Поскольку геттер возвращает ссылку на scores, внешний код, имея эту ссылку, может вносить изменения в массив.

Решение этой проблемы заключается в том, что геттеру необходимо возвращать копию объекта, а не ссылку на оригинал. Модифицируем вышеупомянутый геттер следующим образом:

Переменные примитивных типов вы можете свободно передавать/возвращать прямо в сеттере/геттере, потому что Java автоматически копирует их значения. Таким образом, ошибок № 2 и № 3 можно избежать.

 private float amount; public void setAmount(float amount) < this.amount = amount; >public float getAmount()

String — это immutable-тип. Это означает, что после создания объекта этого типа, его значение нельзя изменить. Любые изменения будут приводить к созданию нового объекта String. Таким образом, как и для примитивных типов, вы можете безопасно реализовать геттер и сеттер для переменной String:

 private String address; public void setAddress(String address) < this.address = address; >public String getAddress()

Т.к. объекты класса java.util.Date являются изменяемыми, то внешние классы не должны иметь доступ к их оригиналам. Данный класс реализует метод clone() из класса Object, который возвращает копию объекта, но использовать его для этих целей не стоит.

По этому поводу Джошуа Блох пишет следующее: «Поскольку Date не является окончательным классом, нет га­рантии, что метод clone() возвратит объект, класс которого именно java.util.Date: он может вернуть экземпляр ненадежного подкласса, созданного специально для нанесения ущерба. Такой подкласс может, например, записы­вать ссылку на каждый экземпляр в момент создания последнего в закрытый статический список, а затем предоставить злоумышленнику доступ к этому списку. В результате злоумышленник получит полный контроль над всеми эк­земплярами копий. Чтобы предотвратить атаки такого рода, не используйте метод clone() для создания копии параметра, тип которого позволяет нена­дежным сторонам создавать подклассы».

Источник

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