I can generate getters and setters in java program and I know that it is used to access private variables. Besides this How will I be able to decide this, at this point I need to create java class with getters and setters.
Getter and Setter methods are used for encapsulate the data.
it means wrapping the data into single unit.
For example create a ListView with 3 TextView who has different-different value.
so now the question is how will you send the data to your custom ListView adapter. In this case you have to use a beam(has getter-setter methods) class.
EDIT:
Here is another example it will show how to send multiple data by single object from one Activity to another Activity
https://stackoverflow.com/a/7827593/6676466
in modern java programming you must importantly follow information
hiding this is making the class fields to become private or
protected(to be used by child class) that is why we have getter and setter
method, also getter and setter is useful when you want to have a range check in each data field
if you want to directly access the variable you can create a child class of that parent class and set each fields to become protected
Related
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 5 years ago.
Why do the data members of POJO classes are private and the getter/setter function are public?
Can someone please give solution for this.
Common approach: access to variables by using getters/setters:
better maintainability
accessibility to private properties only for the defining class (isolation)
used for a different data representation (you might have private data to store the birthdate, but create a getter named getAge()).
It doesn't have to be that way, it's just a pattern and it exists for a reason.
All members of a class should be private by default, so that noone can mess up things from outside or read/write values which are not important by the outside. Additionally some internal stuff can change within your class, and the outside world should not care about it.
To allow access from the 'outside world', be it reading or writing anything should be handled via getters/setters/issers to allow a governed manipulation.
Think of it like a mini API of your class - an interface to your class anyone outside can understand and rely on.
If you want to add any validation or modify any other thing before/after setting value of an object, you can use that validation in setter method. Same applies for getter.
It the basic object-oriented principle i.e only object can communicate through message which is called encapsulation.So indirectly you are not exposing your state to outside.For an example class with one attribute age is there and age can not be negative so in setter you can put a check so your object state will not in bad condition.If you access directly the variable then there is no scope for validation.
The basic principle of the oriented object programming is to encapsulate the members of a class and give access to them only via getters and setters
I am trying to persist the objects generated by JAXB. Here is the sample structure:
#Column(name = "reporting_identifier")
private String reportingIdentifier;
#Column(name = "apply_quiet_time")
private boolean applyQuietTime;
#Embedded
private RecipientDetailsList recipientDetailsList;
Below is the structure of RecipientDetailsList class:
#ElementCollection(targetClass=String.class)
private List<RecipientDetails> recipientDetails;
Now, the RecipientDetails class has one argument constructor, which accepts a String. That String I want to persist in the database as a part of the whole record. I am seeing
org.hibernate.InstantiationException: No default constructor for entity: RecipientDetailsList
exception when I try to save an object. I have two questions:
Do we have any work around this exception? I can't change the class as it is designed for JAXB marshalling/unmarhsalling. Can I somehow store the objects without altering the structure? Also, I am interested in only storing the first record of the list referenced by
recipientDetails as I want only one row for object. I want it to ignore the rest of the records if it has more than 1 record. Is it possible?
Is this good design to use the annotation directly into classes which are generated by JAXB? Should I create another classes (and possibly mappers/converters) just to store and retrieve the information?
For your first question: this is happening because when Hibernate tries to create a bean, it does it via reflection. It does the object creation by calling the no-arg constructor, and then using the setter methods to set the properties. You can't use a bean that doesn't have a no-arg constructor.
For the second question: if something else has generated classes for you that don't have a no-arg constructor, really your only option (if you can't modify the class) is to create a wrapper round it, or a subclass that has a no-arg constructor. I don't see any other way of doing it if you can't modify the class directly. But the subclassing should be fine as long as the class you've got has enough visibility on the methods (i.e., doesn't have private methods that you then can't get to).
This question already has answers here:
Why Not Use Public Member Functions
(3 answers)
Closed 9 years ago.
I have question which has been going around in my mind since long.
My Model class should have properties private or public? (Below code is written in PHP but question applies in general for any language)
class Xyz extends Model {
public function __call() {
}
public $description;
public $title;
}
In above example I have public properties $description and $title. Should I make them private?
I update my model as follows
$x = new Xyz();
$x->title('Hello');
$x->description('Blah blah');
$x->save();
I can update and get them by using magic method __call. So why do we need to keep them public? I can make them private. But as I see all the frameworks around keep model properties public.
Any thoughts?
UPDATE:
In answers, everyone is saying follow encapsulation and use private methods. Good but no one has the answer why some PHP frameworks have model properties public ? There should be some reason, isn't it?
As per OOP, we need to follow encapsulation. Please make your properties private and have public accessors and mutators. but, it depends that your accessors and mutators can have other modifiers as well. But, The properties should be always private.
Class fields should always be private. Getters and setters for the fields should be public. Aside from being standard, it is also good to have it this way so that you have the control to do what ever you want to the values that the client classes wants to set to you private fields.
For example, if you want to persist an object to a database, and one column is stated to be not null, and you are not sure if your client class will really return a non-null value, you can handle the null check inside the setter so that the values that you are about to persist to the db contains no null field, as what the table of your db demands.
The fields should always be private as per OOP encapsulation principle. Now the thing is with the getter and setter accessor methods.
The getter is usually safe to make it public. The only downside of it is that you will have to maintain backward compatibility between versions, as this will be part of the public contract of the class. So if the field is something that is part of the implementation rather than interface, than maybe you want to keep it protected.
As for the setter the better question is if to create one or not. If you want to keep your class immutable (or at least some parts of it) with all the advantages and disadvantages that comes from it, then you'll not be creating a setter at all.
You have to make all properties as private in model class and if you have to encapsulate their value then you have to use appropriate getters and setters to get and set their values.
Say I have a class Animal and then a bunch of sub-classes that extend Animal. Say I want to have a common field called name that should also exist in each child class. What is the proper way to include and initialize this field in each sub-class?
1) Declare the field in the parent as protected, and then initialize it inside of each sub-class. If I do it this way, is it proper to refer to the field as super.variable or simply variable? Personally to me, using super makes it more obvious that the field is declared in the parent. (This is what I am currently doing)
2) Declare the field in the parent as private and then create getters and setters to access the field
3) Just declare and initialize the same variable in each sub-class
4) Another method I'm missing?
Thanks for the help. I understand this question is fairly basic, but I'm curious of what the most proper style is.
Edit:
I'm not to sure if you guys will see this, but here is a follow up question.
Is there any good way to ensure that the sub-classes initialize the field?
The answer depends on whether you need to control access to that field for correctness (e.g., to make sure that some other field gets updated at the same time). If it's okay for subclasses to twiddle the field directly, then just use protected. If you need to perform additional checks or actions whenever the field is set, you should make it private to the superclass and make the subclass use the setter to ensure your logic is run. You shouldn't duplicate the field if you know that it'll always be needed; if you're not sure, then you should consider using an interface Animal and putting the field on an AbstractAnimal implements Animal.
In Java, you don't use super for anything except to call the superclass's version of a method. Just access protected fields directly; that's what they're there for, and your development environment will keep track of where they're declared if you need to know.
I vote for 2:
Create a private field, and have setters and getters (which can be protected to make them accessible only to subclasses).
Other options if you don't need a setter (just a getter):
4) Abstract getter and leave it up to the subclass how to implement it
5) private final field, set by abstract class constructor, and a getter.
I always make fields protected fields, since this helps debuggability & extensibility, and put public getters & setters on them to make a 'property'.
(Private fields in various open-source libraries, Swing components etc have repeatedly been a hindrance to me when trying to do quite legitimate debugging/ extension engineering. So I'm fairly anti- them.)
If I'm concerned about traceability, where there is possible behaviour or errors involved (such as values being got & cached), I might access the variable in subclasses via the getter.
I always use this.name when writing to variables -- it works well for code clarity, and it simplifies parameter-naming in setters. (Use just name for the parameter & this.name for the field.)
I don't use this when reading variables -- it's the writes I want to be clear about. For collections, I suffix the field with List or map or whatever ie childList -- but the parameter and locals are "children".
I never use super when referring to variables. Super would only make sense to disambiguate inherited & declared variables with the same name, which you can legally do -- but is almost guaranteed to be erroneous for code style, clarity & tends to lead to bugs.
I also like to make most properties mutable -- rather than settable only at construction. This helps if you ever want to use Hibernate, or persist the data. Over-reliance on constructor initialization tends to evolve into difficulties -- large & brittle call-signatures, inability to use the class for partly-formed data or "special value" answers, and order-of-init problems.
I think it depends on the situation. If the name field should be publicly accessible, I would declare the field as private and then make public get/set methods. Sometimes you want to expose fields on the base class as part of the public interface of the derived classes.
If the name field should only be used inside the derived classes I would just go with a protected field.
If you want to be sure that a subclass initializes a field add a parameter in the base class constructor, then initialize the field in the base class using the argument supplied by the derived classes constructor.
I usually using option 2 (private + accessors - protected,not necessary public) to have a chance to customize variable access.
About your edit: Force in constructor name if it is a mandatory requirement
Animal(String name) {
this.name = name;
}
or
String getName() {
if(null == name){
name = initializeName();
}
return name;
}
and make initializeName() abstract
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I saw a code where getters and setters methods are declared private. I am trying to figure out the logic behind it, and I am really having hard time to understand why would you declare them as private? That's exactly opposite of what we are trying to achieve through getters and setters.
I can think of several reasons:
you want to prevent future public access.
If a different programmer sees your code and wants access to a variable, but there are no setters and getters, he might think you just forgot about them, and add them themselves. However, if you declare them as private, it's a statement of intent, saying I don't want these variables to be changed or accessed from the outside.
you want to associate setting and getting with other actions
Say you don't want public accessors. But maybe you want a count of how many times a private variable is changed. It's easier to use a setter rather than incrementing the count every time you access that variable.
you want a central access point
Again, you don't want public access, but during debugging, you might want to put a breakpoint in every place a private member is changed. So instead of setting breakpoints everywhere in the class, you just set one in the accessor.
That's exactly opposite of what we are trying to achieve through getters and setters.
Actually, it is not. The reason for declaring public getters and setters is to hide the fields. This is done to avoid unwanted coupling; i.e. clients of an API depending on the implementation details of the API. (That coupling can be problematic for a number of reasons. For example, dependencies on the types of the fields, the possibility of unexpected changes to the fields.)
The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.
While the case for using getters and setters is not as strong for private state, there are still tangible benefits in using private getters and/or setters. For instance:
The private getter/setter methods provide a place for adding extra behavior or error checking code.
They can provide a place for logging state changes or access to the fields.
They can provide a place for adding your debug code while testing. (Probably not the best way of debugging.)