For the use in a Servlet based application I've written a class to store a view name and objects to be rendered. Actually it is more a data structure than a class in the sense of OOP. I wonder if I should expose the members or if should use getters.
public class Result {
private final int status;
private final String view;
private final Map<String, Object> model = new HashMap<String, Object>();
public Result(final int status, final String view) {
this.status = status;
this.view = view;
}
public Result put(final String modelName, final Object modelObject) {
model.put(modelName, modelObject);
return this;
}
}
Should I add getStatus(), getView() and getModel() or should I change the member visibility to "public"? At the moment I don't know any scenario where it would be useful to have a method to access a member. "Result" is an immutable datastructure and no computations are needed when members are accessed. Would you add getters for the unlikely event that the implementation changes?
Addendum
I read a section related to my question in Robert C. Martins excellent book Clean Code (page 99):
Hybrids
This confusion [about objects and data structures] sometimes lead to
unfortunate hybrid structures that are
half object and half data structure.
They have functions that do
significant things, and they also have
either public variables or public
accessors and mutators that, for all
intents and purposes, make the private
variable public, tempting other
external functions to use those
variables the way a procedural program
would use a data structure.
Such hybrids make it hard to add new
functions but also make it hard to add
new data structures. They are the
worst of both worlds. Avoid creating
them. They are indicative of muddled
design whose authors are unsure of -
or worse, ignorant of - whether they
need protection from functions or
types.
For a data-holder class creating getters or not is a matter of taste. Based on your description you can make the visibility public or package on status and view, but I would add a getter for retrieving a model by name. Although the map is final, its contents is not.
Edit
I meant something like:
public Object get(final String modelName) {
return model.get(modelName);
}
There is no reason to make the model map visible. (I would name the map "models" and use setModel(name, model) and getModel(name) as accessors.)
I can't make concrete recommendations as it would depend on how you're going to be using that class. However...
I often create "lightweight" objects intended as data structures to transport some immutable data. Like you, I make the members public final and initialize them in the constructor.
The risks associated with accessible, mutable data members aren't there when they're final; all you're losing is the ability to meaningfully subclass the class. Also, you can't attach functionality to data access. But for a lightweight data transfer object, chances are you won't be doing that anyway.
You say:
At the moment I don't know any
scenario where it would be useful to
have a method to access a member.
That's precisely why I'd advocate accessing the data via getters. At the moment you're using the object to store corresponding objects in your model. However your model may well change in the future, and yet you may want to display the data in the view in the same fashion.
Given that, and the headache in testing the view component of an MVC, I would always implement the getter/setter mechanism.
Related
JEP-395 says
a record class acquires many standard members automatically:
For each component in the header, two members: a public accessor method with the same name and return type as the component, and a private final field with the same type as the component;
If a generated final field has got the same name as the accessor method, why isn't a public final field generated instead?
Record components would be barely and carefully changed since Instances of record classes can be serialized and deserialized. However, the process cannot be customized by providing writeObject, readObject, readObjectNoData, writeExternal, or readExternal methods
So changing API internal implementation(record component) would not be an appropriate reason. But I've got good reason from #Brian Goetz
Thank you all to have attention to my fool question
Records can implement interfaces, so the accessor of a record could be an implementation of an interface method. Furthermore using accessors instead of direct field access provides more flexibility, for example you can replace an accessor that directly returns a field with an accessor that derives a value in some way (or vice versa).
Records also allow you to override accessors to - instead of just plainly returning the field - to do something extra. Making records use direct field access would restrict and limit what you could do with records, and thus limit their usefulness, while having accessors offers you the baseline offered by direct field access with the ability to do more if necessary.
To quote an example provided by Holger in the comments:
the classes public record R(int a, int b) { public int c() { return …; }} and public record R(int a, int c) { public int b() { return …; }} provide the same API, regardless of their internal representation.
In short, generating accessors for fields offers more flexibility and features than direct field access. The same also applies to plain immutable classes.
Another reason is provided by Brian Goetz in the comments on this answer:
Without the ability to override accessors, records would be unable to
properly support mutable objects (such as arrays) as components. If
you have an array component, you may want to perform a defensive copy
in the constructor and accessor (which would also require overriding
equals, in order to preserve the specification of Record); if it was a
public final field, you could not encapsulate the mutability of your
components
I think a key factor in this decision was that you now have the ability to override the Record's getters:
public record MyRecord(String myProperty) {
#Override
public String myProperty() {
return "The property is " + myProperty;
}
}
Something like this would not be possible with public final fields.
It's generally best practice to use accessor methods instead of direct field access. Even with records, it makes sense to continue that practice to allow for, say, renaming your fields without breaking existing code.
Java programmers are absolutely addicted to needless encapsulators. They look at a public final field and recoil in superstitious revulsion. So we get people making crazed knee-jerk statements like "There is no point in accessing your fields directly (basic fundamental of programming- encapsulation)", together with kooky reasoning that it is sound to mandate a naming convention (get/set and bizarrely is) as the only correct way to address a datum - despite the fact that you have no idea what those method implementations actually do.
Of course, the reason it persists it because of the language's baffling decision to not implement properties as a built-in feature of the language (a la C#, Kotlin) at any point in the past 30 years. Instead, spending a decade making repeated abortive attempts at modularization of the language (a practically unused feature since it finally arrived).
The introduction of Records would have been the perfect opportunity to implement properties properly once and for all (it's a pifflingly simple enhancement, after all - implement it in the desugar pass of the compiler and it's a day's work, I've done it myself; another couple of days to add property listener support to all accessible fields). But still, no.
So, rant over, back to the question. Public final fields would have been a more sensible implementation, with an option to make the field private (record R (private int foo, int bar)) where encapsulation was absolutely required. Better yet, automatic wrapping of collections/maps in immutable decorators could have been implemented easily (declare List and the auto-generated constructor ensures the field receives an immutable List), removing the only compelling argument for auto-encapsulating an immutable POJO field.
But it would have run contrary to a (faulty) prejudice against public final fields which is endemic in the Java community.
What is the difference between following two class in terms of data hiding(encapsulation).
In below example , I can access the value of member by making it public.
Eg: 1
public class App {
public int b = 10;
public static void main(String[] args) {
System.out.println(new App().b);
}
}
In below example, I can access the value of member by using getter method.
Eg : 2
class DataHiding
{
private int b;
public DataHiding() {
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
In both the above examples, I can access the value of member. Why Eg : 2, is called data hiding (encapsulation) ? If its not hiding the data.
Why Eg : 1 is not called encapsulated ?
What is it about
As you tagged this question with both java and object oriented programming oop, I suppose you are implicitly thinking about Java Beans. Nevertheless this is a question quite common across languages, take the wikipedia page on this matter :
In programming languages, encapsulation is used to refer to one of two
related but distinct notions, and sometimes to the combination1
thereof:
A language mechanism for restricting access to some of the object's
components.
A language construct that facilitates the bundling
of data with the methods (or other functions) operating on that
data.
Some programming language researchers and academics use the first
meaning alone or in combination with the second as a distinguishing
feature of object-oriented programming, while other programming
languages which provide lexical closures view encapsulation as a
feature of the language orthogonal to object orientation.
The second definition is motivated by the fact that in many OOP
languages hiding of components is not automatic or can be overridden;
thus, information hiding is defined as a separate notion by those who
prefer the second definition.
So encapsulation is not really about hiding data or information it about enclosing pieces of data in a language component (a class in Java). A Java Beans encapsulate data.
That being said, while encapsulation is one of the main feature of object oriented programming paradigm, at some point in the history of language design it was seen as not enough to help design better software.
History
One key practice to achieve better software design is decoupling, and encapsulation helps on that matter. Yet a cluster of data was not enough to help achieve this goal, other efforts in OOP pioneering were made in different language at that time, I believe SIMULA is the earliest language to introduce some kind of visibility keywords among other concepts like a class. Yet the idea of information hiding really appears later in 1972 with data that is only relevant to the component that uses it to achieve greater decoupling.
But back to the topic.
Answers to your questions
In this case data is encapsulated and public
This is commonly known as a global variable and it is usually regarded as a bad programming practice, because this may lead to coupling and other kind of bugs
Data is encapsulated and public (through method accessors)
This class is usually referred to as a Java Bean, these are an abomination if used in any other than what they were designed for.
These object were designed to fulfill a single role and that is quite specific is according to the specification
2.1 What is a Bean?
Let's start with an initial definition and then refine it:
“A Java Bean is a reusable software component that can be manipulated visually in a builder tool.”
Why is it an abomination nowadays ? Because people, framework vendors usually misuse them. The specification is not enough clear about that, yet there's some statement in this regard :
So for example it makes sense to provide the JDBC database access API as a class library rather than as a bean, because JDBC is essentially a programmatic API and not something that can be directly presented for visual manipulation.
I'd rather quote Joshua Bloch (more in this question and answer) :
"The JavaBeans pattern has serious disadvantages." - Joshua Bloch, Effective Java
Related points
As explained above one key practice to achieve better software is decoupling. Coupling has been one of the oldest battlefront of software engineers. Encapsulation, information hiding have a lot to do with the following practices to help decoupling for numerous reasons:
the Law of Demeter, breaking this law means the code has coupling. If one has to traverse a whole data graph by hand then, there's no information hiding, knowledge of the graph is outside of the component, which means the software is therefore less maintainable, less adaptable. In short : refactoring is a painful process. Anemic domain model suffer from that, and they are recognized as an anti-pattern.
A somehow modern practice that allows one to not break the Law of Demeter is Tell, Don't Ask.
That is, you should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do.
immutability, if data has to be public it should be immutable. In some degree if data is not needed, one module can introduce side effects in another ; if this was true for single threaded programs, it's even more painful with multi-threaded softwares. Today softwares and hardware are getting more and more multi-threaded, threads have to communicate, if an information has to be public it should be immutable. Immutability guarantee thread-safety, one less thing to worry about. Also immutability has to be guaranteed on the whole object graph.
class IsItImmutable {
// skipping method accessors for brevity
// OK <= String is immutable
private final String str;
// NOK <= java.util.Date is mutable, even if reference is final a date can be modified
private final Date date;
// NOK <= Set operations are still possible, so this set is mutable
private final Set<String> strs;
// NOK <= Set is immutable, set operations are not permitted, however Dates in the set are mutable
private final Set<Date> udates = Collections.unmodifiableSet(...);
// OK <= Set is immutable, set operations are not permitted, String is immutable
private final Set<String> ustrs = Collections.unmodifiableSet(...);
}
Using mutators and accessors hides the logic, not the name of the methods. It prevents users from directly modifying the class members.
In your second example, the user has no idea about the class member b, whereas in the first example, the user is directly exposed to that variable, having the ability to change it.
Imagine a situation where you want to do some validation before setting the value of b, or using a helper variable and methods that you don't want to expose. You'll encapsulate the logic in your setter and by doing that, you ensure that users cannot modify the variable without your supervision.
Encapsulation is not data hiding it is information hiding. You are hiding internal structure and data implementation, as well as data access logic.
For instance you can store your integer internally as String, if you like. In first case changing that internal implementation would mean that you have to also change all code that depends on b being an int. In second case accessor methods will protect internal structure and give you int, and you don't have to change the rest of the code if internals have changed.
Accessor methods also give you opportunity to restrict access to the data making it read-only or write-only in addition to plain read-write access. Not to mention other logic that can verify integrity of data going into the object as well as changing object state accordingly.
What happens if you want to retrieve the state of B without being able to change its value? you would create the getter but not the setter, you can't accomplish that by accessing B as a public int.
Also, in both methods get and set, if we had a more complex object, maybe we want to set or get some property or state of the object.
Example.
private MyObject a;
public setMyObjectName(String name){
MyObject.name = name;
}
public getMyObjectName(){
return MyObject.name;
}
This way we keep the object encapsulated, by restricting access to its state.
In java, all methods are virtual. This means, that if you extend some class, you can override the result of a method. Imagine for example the next class (continuing on your example):
class DataHidingDouble extends DataHiding{
public int getB(){
return b*2;
}
}
this means that you maintain control over what b is to the outer world in your subclass.
imagine also some subclass where the value of b comes from something that is not a variable, eg. a database. How are you then going to make b return the value if it is a variable.
It hides the data, not the value. Because the class is responsible for maintaining the data, and returning the correct value to the outside world.
This question already has answers here:
Get and Set methods in Java. How do they work?
(5 answers)
Closed 7 years ago.
Can somebody tell me or show me something that would make me understand the get and set methods completely? I know some of it already but it still confuses me.
I am trying to learn the MVC Design Pattern but I find it hard because I haven't completely understand this. I thought it was easy but it's not really that easy. Well, at least for me.
Your own example would be appreciated. Thank you in advance guys :)
The Model, View, Controller design pattern is a useful way of decoupling the various components of an GUI driven application. It improves cohesion, which essentially emphasises the responsibility of discrete elements of your software and helps avoid unnecessary overlapping of functionality.
The Model stores what is referred to as 'business logic'. This means it houses all of the data which is core to your application.
The View is what handles the graphical interface. Everything responsible for managing how your graphics are rendered is defined here.
Finally, the Controller handles events. This includes asynchronous events such as whenever a key has been pressed, or the mouse has been moved, or the user has touched their screen. It receives these events and decides what to do with them.
So, how they come together is as follows; the Model defines what needs to be drawn. Any graphics the View needs to render is therefore housed in the Model. This means that any modifications to the Model's data will in turn effect what is drawn on the screen; however, the Model is only really defining what elements need to be drawn, it has no clue how to draw them; just how to manage them and manipulate them. It's the View which can take these elements and in turn use them within a graphical context. The controller on the other hand, handles events and in turn manipulates the contents of the Model. It does this by using a defined set of rules on how each input event will affect certain parts of the Model.
So, in this regard, the Model, View, Controller can be looked at like this:
final Model m = new Model();
final View v = new View(m);
final Controller c = new Controller(m);
Both the Controller and View need access to the Model in order to manage and render the application respectively, but the Model doesn't care about either of them. This is because the Model defines the core data dependencies of your application, which should be transferrable, and work independently of whether it's a component of a GUI or not.
In terms of getter and setter methods, all these do are provide access to a member variable sitting inside a class. So if we were to look inside the View, we would see something like this:
public final class View {
/* Member Variables. */
private final Model mModel;
public View(final Model pModel) {
/* Initialize Member Variables. */
this.mModel = pModel;
}
public final Model getModel() {
return this.mModel;
}
}
The method getModel() is referred to as a getter method; it's sole responsibility is to return a variable; in this case it returns the View's mModel variable. What's useful about getter and setter methods is that you can control access to that variable; the method can be declared public, protected and private for example, which all change just who else inside your application can get access to the Model. The same goes for a setter method, whose only responsibility should be to change the value of a specific variable belonging to the owning Object.
I know this should be a comment, but I currently don't have the reputation required to post a comment.
First of all, could you please provide more information about what specifically you'd like to know? Are you confused about how getters and setters work in general? Are you confused about how the work in an MVC pattern? (getters and setters work the same way in MVC as they do in other design patterns).
If the link posted in the comment above doesn't solve your answer, then hopefully I can help. Getters and setters (getVarName and setVarName) are used to provide additional functionality (like ensuring that a value fits a desired range, etc) and also to provide encapsulation of your code. Besides the additional functionality (like validation), encapsulation also helps avoid errors like accidentally changing the value of a class's variable when you don't mean to. Take a Customer class for example:
public class Customer {
private int empNo;
private int deptNo;
//additional class variables
public Customer() {
//default constructor }
public Customer (int emp, int dept) {
empNo = emp;
deptNo = dept;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int emp) {
empNo = emp;
}
//other methods
}
Let's say that all employee numbers must be 5 digits long and not start with a 0. If we don't use a setter, then there's no way to check if the number given is a valid number (or that it was even given). For that, we could write a simple validation requirement in our setEmpNo method.
public void setEmpNo(int emp) {
if(emp >= 10000 && emp <= 99999) {
empNo = emp;
}
//code to handle invalid numbers
}
Encapsulation also helps us avoid certain errors, like changing the value of empNo when we mean to just check the value in a condition, etc. For instance, if we don't use getters and setters and just have a public empNo, the following typo would change the value of the employee's employee number:
if(employee1.empNo = 12345) { //checking if this is employee 12345 would use ==
//perform action for specified employee
}
However, if we use getters and setters, we'd still run into a problem because we're not checking if the desired employee's employee number is 12345, but that employee's number would NOT be permanently changed to 12345 and would still retain his/her correct employee number. Does this make sense?
It looks like someone already posted a pretty good answer about MVC, so I won't repeat any info on that. One thing I will point out is that MVC is usually (if not always) used for server-based apps. If you have an app that contains a website that users interact with and a database, then there's a good chance you'll use some variant of the MVC pattern. However, you're not going to use MVC for something like a Hello World app.
I hope my answer isn't too basic. It's hard to judge a user's knowledge level without getting additional info. If you'd like me to clarify or give further explanation on anything I've posted, let me know.
Best of luck going forward.
Getter and setter methods used when we define instance variables private so from outside class we can't access private instance variables directly which is useful for encapsulation(hiding data from outside world). So for accessing private variables we required some methods which is basically getter and setter.
public class Employee
{
private int empNum;
public Employee(int empNum) {
this.empNum = empNum;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
}
for more reasons why we use getter/setter read this answer
There is no direct relation between MVC and getter/setter methods.
MVC is basically design patter for software development where we divide task between different modules(model, view and controller)
model -> Data layer
view -> Representational layer
controller -> Controller layer between model and view
So when you create model class in mvc you define multiple instance variables(attributes) for model but from controller you don't want to access that variables directly so in that case you should use getter setter methods.
Actually getter/setter concept in not limited to just mvc it is use as a codding standard and for abstraction purposes.
I've been reading the book Clean Code: A Handbook of Agile Software Craftsmanship and in chapter six pages 95-98 it clarifies about the differences between objects and data structures:
Objects hide their data behind abstractions and expose functions that operate on that data. Data structures expose their data and have no meaningful functions.
Object expose behavior and hide data. This makes it easy to add new kinds of objects without changing existing behaviors. It also makes it hard to add new behaviors to existing objects.
Data structures expose data and have no significant behavior. This makes it easy to add new behaviors to existing data structures but makes it hard to add new data structures to existing functions.
I'm a tad bit confused whether some classes are objects or data structures. Say for example HashMaps in java.util, are they objects? (because of its methods like put(), get(), we dont know their inner workings) or are they data structures? (I've always thought of it as data structures because its a Map).
Strings as well, are they data structures or objects?
So far majority of the code I've been writing have been the so called "hybrid classes" which try to act as an object and a data structure as well. Any tips on how to avoid them as well?
The distinction between data structures and classes/objects is a harder to explain in Java than in C++. In C, there are no classes, only data structures, that are nothing more than "containers" of typed and named fields. C++ inherited these "structs", so you can have both "classic" data structures and "real objects".
In Java, you can "emulate" C-style data structures using classes that have no methods and only public fields:
public class VehicleStruct
{
public Engine engine;
public Wheel[] wheels;
}
A user of VehicleStruct knows about the parts a vehicle is made of, and can directly interact with these parts. Behavior, i.e. functions, have to be defined outside of the class. That's why it is easy to change behavior: Adding new functions won't require existing code to change. Changing data, on the other hand, requires changes in virtually every function interacting with VehicleStruct. It violates encapsulation!
The idea behind OOP is to hide the data and expose behavior instead. It focuses on what you can do with a vehicle without having to know if it has engine or how many wheels are installed:
public class Vehicle
{
private Details hidden;
public void startEngine() { ... }
public void shiftInto(int gear) { ... }
public void accelerate(double amount) { ... }
public void brake(double amount) { ... }
}
Notice how the Vehicle could be a motorcycle, a car, a truck, or a tank -- you don't need to know the details. Changing data is easy -- nobody outside the class knows about data so no user of the class needs to be changed. Changing behavior is difficult: All subclasses must be adjusted when a new (abstract) function is added to the class.
Now, following the "rules of encapsulation", you could understand hiding the data as simply making the fields private and adding accessor methods to VehicleStruct:
public class VehicleStruct
{
private Engine engine;
private Wheel[] wheels;
public Engine getEngine() { return engine; }
public Wheel[] getWheels() { return wheels; }
}
In his book, Uncle Bob argues that by doing this, you still have a data structure and not an object. You are still just modeling the vehicle as the sum of its parts, and expose these parts using methods. It is essentially the same as the version with public fields and a plain old C struct -- hence a data structure. Hiding data and exposing methods is not enough to create an object, you have to consider if the methods actually expose behavior or just the data!
When you mix the two approaches, e.g. exposing getEngine() along with startEngine(), you end up with a "hybrid". I don't have Martin's Book at hand, but I remember that he did not recommend hybrids at all, as you end up with the worst of both worlds: Objects where both data and behavior is hard to change.
Your questions concerning HashMaps and Strings are a bit tricky, as these are pretty low level and don't fit quite well in the kinds of classes you will be writing for your applications. Nevertheless, using the definitions given above, you should be able to answer them.
A HashMap is an object. It exposes its behavior to you and hides all the nasty hashing details. You tell it to put and get data, and don't care which hash function is used, how many "buckets" there are, and how collisions are handled. Actually, you are using HashMap solely through its Map interface, which is quite a good indication of abstraction and "real" objects.
Don't get confused that you can use instances of a Map as a replacement for a data structure!
// A data structure
public class Point {
public int x;
public int y;
}
// A Map _instance_ used instead of a data structure!
Map<String, Integer> data = new HashMap<>();
data.put("x", 1);
data.put("y", 2);
A String, on the other hand, is pretty much an array of characters, and does not try to hide this very much. I guess one could call it a data structure, but to be honest I am not sure if much is to be gained one way or the other.
This is what, I believe, Robert. C. Martin was trying to convey:
Data Structures are classes that simply act as containers of structured data. For example:
public class Point {
public double x;
public double y;
}
Objects, on the other hand, are used to create abstractions. An abstraction is understood as:
a simplification of something much more complicated that is going on under the covers The Law of Leaky Abstractions, Joel on Software
So, objects hide all their underpinnings and only let you manipulate the essence of their data in a simplified way. For instance:
public interface Point {
double getX();
double getY();
void setCartesian(double x, double y);
double getR();
double getTheta();
void setPolar(double r, double theta);
}
Where we don't know how the Point is implemented, but we do know how to consume it.
As I see it , what Robert Martin tries to convey, is that objects should not expose their data via getters and setters unless their sole purpose is to act as simple data containers. Good examples of such containers might be java beans, entity objects (from object mapping of DB entities), etc.
The Java Collection Framework classes, however, are not a good example of what he's referring to, since they don't really expose their internal data (which is in a lot of cases basic arrays). It provides abstraction that lets you retrieve objects that they contain. Thus (in my POV) they fit in the "Objects" category.
The reasons are stated by the quotes you added from the book, but there are more good reasons for refraining from exposing the internals. Classes that provide getters and setters invite breaches of the Law of Demeter, for instance. On top of that, knowing the structure of the state of some class (knowing which getters/setters it has) reduces the ability to abstract the implementation of that class. There are many more reasons of that sort.
An object is an instance of a class.
A class can model various things from the real world. It's an abstraction of something (car, socket, map, connection, student, teacher, you name it).
A data structure is a structure which organizes certain data in a certain way.
You can implement structures in ways different that by using classes (that's what you do in languages which don't support OOP e.g.; you can still implement a data structure in C let's say).
HashMap in java is a class which models a map data structure using hash-based implementation, that's why it's called HashMap.
Socket in java is a class which doesn't model a data structure but something else (a socket).
A data structure is only an abstraction, a special way of representing data. They are just human-made constructs, which help in reducing complexity at the high-level, i.e. to not work in the low-level. An object may seem to mean the same thing, but the major difference between objects and data structures is that an object might abstract anything. It also offers behaviour. A data structure does not have any behaviour because it is just data-holding memory.
The libraries classes such as Map, List,etc. are classes, which represent data structures. They implement and setup a data structure so that you can easily work with them in your programs by creating instances of them (i.e. objects).
Data structures(DS) are an abstract way of saying that a structure holds some data'. HashMap with some key value pairs is a data structure in Java. Associated arrays are similarly in PHP etc. Objects is a little lower than the DS level. Your hashmap is a data structure. now to use a hashmap you create an 'object' of it and add data to that object using put method. I can have my own class Employee which has data and is thus a DS for me. But to use this DS to do some operations like o see if the employee is a male or a female colleague i need an instance of an Employee and test its gender property.
Don't confuse objects with data structures.
An object is an instance of a class. A class can define a set of properties/fields that every instance/object of that class inherits. A data structure is a way to organize and store data. Technically a data structure is an object, but it's an object with the specific use for holding other objects (everything in Java is an object, even primitive types).
To answer your question a String is an object and a data structure. Every String object you create is an instance of the String class. A String, as Java represents it internally, is essentially a character array, and an array is a data structure.
Not all classes are blueprints for data structures, however all data structures are technically objects AKA instances of a class (that is specifically designed to store data), if that makes any sense.
Your question is tagged as Java, so I will reference only Java here.
Objects are the Eve class in Java; that is to say everything in Java extends Object and object is a class.
Therefor, all data structures are Objects, but not all Objects are data structures.
The key to the difference is the term Encapsulation.
When you make an object in Java, it is considered best practice to make all of your data members private. You do this to protect them from anyone using the class.
However, you want people to be able to access the data, sometimes change it. So, you provide public methods called accessors and mutators to allow them to do so, also called getters and setters. Additionally, you may want them to view the object as a whole in a format of your choosing, so you can define a toString method; this returns a string representing the object's data.
A structure is slightly different.
It is a class.
It is an Object.
But it is usually private within another class; As a Node is private within a tree and should not be directly accessible to the user of the tree. However, inside the tree object the nodes data members are publicly visible. The node itself does not need accessors and mutators, because these functions are trusted to and protected by the tree object.
Keywords to research: Encapsulation, Visibility Modifiers
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 9 years ago.
Consider the following Java code:
public class SomeClass{
private int data;
public void setData(int data){
this.data = data;
}
public int getData(){
return this.data;
}
}
In the above code the value of data can be accessed from anywhere. So why not just make the field data public?
Why Getters and Setters?
Many people wonder why we need accessor and mutator methods in Java (a.k.a. getters and setters), why can’t we just access the data directly? But the purpose of encapsulation here is is not to hide the data itself, but the implementation details on how this data is manipulated. So, once more what we want is a way to provide a public interface through which we can gain access to this data. We can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, we compromise encapsulation, and therefore, the capacity of changing the ways to manipulate this data in the future without affecting its users. We would create a dependency with the data itself, and not with the public interface of the class. We would be creating a perfect cocktail for trouble when “change” finally finds us.
There are several compelling reasons why we might want to encapsulate access to our fields. The best compendium of these reasons I have ever found is described in Joshua Bloch’s book Effective Java. There in Item 14: Minimize the accessibility of classes and members, he mentions several reasons, which I mention here:
You can limit the values that can be stored in a field (i.e. gender must be F or M).
You can take actions when the field is modified (trigger event, validate, etc).
You can provide thread safety by synchronizing the method.
You can switch to a new data representation (i.e. calculated fields, different data type)
You could make a field read-only
Etc.
However, it is very important to understand that encapsulation is more than hiding fields. In Java we can hide entire classes, by this, hiding the implementation details of an entire API.
My understanding of this important concept was broaden and enriched by my reading of a great article by Alan Snyder called Encapsulation and Inheritance in Object-Oriented Programming Languages which I recommend to all readers.
Because you can control how other classes set the data.
You can preform checks on the inputs, or even modify the input according to certain rules you could have.
For example:
public class SomeClass{
private int data;
public void setData(int data){
if (data < 1000){
this.data = data;
}
else{
data = -1;
}
}
public int getData(){
return this.data;
}
}
Even if it looks like there's no point in using the getter/setter methods now, since they don't do anything interesting, you need to think about what might happen in the future when the requirements change. You might find that you need to add some validation when setting the value; you might find that you need to change the whole implementation so that the "get" method is actually going to compute a value from several pieces of data, or read it from a file, or something. And when this happens, if you have other classes that are accessing data directly, you will be screwed. You won't be able to change the implementation the way you need to, without a whole lot of pain. I speak from long, bitter experience going through the pain of maintaining other people's sloppy code.
Sometimes the situation demands that some variables can access for read or write only purpose. You can achieve it through getter and setter method.
If you make the variable public then it can be access and can be changed its value using class object.
This type of pattern is call POJO. POJO is an acronym for Plain Old Java Object. The name is used to emphasize that a given object is an ordinary Java Object, not a special object.
This Link can be answered your question and google up the advantages of POJO class for more info.