A source I am reading says that the keyword private means a method or variable is private at the class level, not the object level.
Meaning in a chunk of code like this:
public class Weight2 implements Comparable<Weight2>
{
private int myPounds, myOunces;
public Weight2()
{
myPounds = myOunces = 0;
}
public Weight2(int x, int y)
{
myPounds = x;
myOunces = y;
}
public int compareTo(Weight2 w)
{
if(myPounds<w.myPounds)
return -1;
if(myPounds>w.myPounds)
return 1;
if(myOunces<w.myOunces)
return -1;
if(myOunces>w.myOunces)
return 1;
return 0;
}
}
A Weight2 object can access the private fields of a different weight2 object without an accessor method... but rather by just saying w.myPounds.
CLARIFICATION:
I want to know from where objects can access a different object's private data. Is it only from within the class? Or could this be done from a driver program?
A source I am reading says that the keyword private means a method or
variable is private at the class level, not the object level.
I don't know your source. It is not wrong but it is not clear either.
You could refer to the JLS that bring this information about the private modifier :
Chapter 6. Names
6.6.1. Determining Accessibility
... the member or constructor is declared private, and access is
permitted if and only if it occurs within the body of the top level
class (§7.6) that encloses the declaration of the member or
constructor.
About :
So what I mean to ask is, can objects of the same type access each
other's private fields without accessor methods?
Indeed.
And it is rather consistent with the specification.
It doesn't restrict the access to private members to only the current instance.
So, you may consider that this limitation doesn't exist and so you can invoke private method for current instance or any variable referencing the current class.
And it is of course true in static as in instance contexts.
As a side note, you should also take into consideration the level access: class and instance.
The private static modifiers means a method or variable is private at the class level. So, you don't need any instance to refer it.
While the private modifier (without the static modifier) means a method or variable is private at the instance level.
So you need an instance to refer it.
So what I mean to ask is, can objects of the same type access each
other's private fields without accessor methods?
Yes, they can.
Access modifiers in Java are about Class'es, not about instances.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Not entirely sure what your question is exactly. However I will give you a basic summary of what i think you want.
If a variable or a method is private then it can only be accessed or used within the class in which it exists.
If a variable or a method is public then it can be accessed by other classes.
Have a look at this website it may assist you it certainly helped me.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
I try to understand a lot of times but I failed to understand this.
Encapsulation is the technique of making the fields in a class private
and providing access to the fields via public methods. If a field is
declared private, it cannot be accessed by anyone outside the class,
thereby hiding the fields within the class.
How can we change the values of fields through setter methods? How do we prevent accessing the fields directly? What is the real use of encapsulation?
Assume you have an age property.
The user can enter a value of -10, which although is a valid number, is an invalid age. A setter method could have logic which would allow you to catch such things.
Another scenario, would be to have the age field, but hide it. You could also have a Date of Birth field, and in it's setter you would have something like so:
...
private int age
private Date dob
...
public void setDateOfBirth(Date dob)
{
this.dob = dob;
age = ... //some logic to calculate the age from the Date of Birth.
}
I have also been confused like you too for a long time until I read the book Encapsulation and Inheritance in Object-Oriented Programming Language and a website that explained the importance of Encapsulation. I was actually directed from the website to the book.
People always say encapsulation is "hiding of information" therefore, maybe, making encapsulation focus on security as the main use. Yes you are hiding information in practice, but that should not be the definition as it could confuse people.
Encapsulation is simply "minimizing inter-dependencies among separately-written modules by defining strict external interfaces" (quoting from the book). That is to say that when I am building a module, I want a strict contract between my clients and me on how they can access my module. Reason being that, I can improve the inner workings without it AFFECTING my client's, life, application or whatever they are using my module for. Because their "module" does not exactly depend on the Inner workings of my module but depends on the "external interface", I made available to them.
So, if I don't provide my client with a setter and give them direct access to a variable, and I realize that I need to set some restriction on the variable before my client could use it, me changing it, could be me, changing the life of my client, or application of my client with HUGE EXPENSE. But if I provided the "strict contract" by creating a "strict external interface" i.e setter, then I can easily change my inner workings with very little or no expense to my clients.
In the setter situation (using encapsulation), if it happens that when you set a variable, and I return a message informing you that it has been assigned, now I could send a message via my "interface", informing my client of the new way my module have to be interacted with, i.e "You cannot assign negative numbers" that is if my clients try to assign negative number. But if I did not use encapsulation, and gave my client direct access to a variable and I do my changes, it could result in a crashed system. Because if the restriction I implemented, is that, you could not save negatives and my client have always been able to store negatives, my clients will have a crashed system in their hands (if that "crashed system" was a banking system, imagine what could happen).
So, encapsulation is more about reducing dependency between module, and an improvement can be made "quietly" with little or no expense to other modules interacting with it, than it is of security. Because the interacting modules depend on the "strict external interface or strict contract".
I hope this explains it properly. If not you could go the links below and read for yourself.
encapsulation matters
Encapsulation and Inheritance in Object-Oriented Programming Languages
The real use of encapsulation is also in the fact that you can do additional checks/processing on the way the values are set.
You're not exactly preventing access to the fields -- you're controlling how others can access certain fields. For example you can add validation to your setter method, or you can also update some other dependent field when the setter method of a field is called.
You can prevent write or read access to the field (e.g. by only providing a getter or setter respectively) -- but encapsulation with properties allows you to do more than just that.
If you have private fields they can't be accessed outside the class, that means basically those fields don't exist to the outside world and yes you can change their value through setter methods but using setter methods you have more flexibility/control to say who gets to change the fields and to what value can they be changed to...basically with encapsulation you get to put restrictions on how and who changes your fields.
For example you have: private double salary, you setter method could restrict that only hr staff can change the salary field it could be written as:
void setSalary(Person p,double newSalary)
{
//only HR objects have access to change salary field.
If(p instanceof HR && newSalary>=0)
//change salary.
else
S.o.p("access denied");
}
Imagine if salary was public and could be access directly any can change it however and whenever they want, this basically the significance of encapsulation
The main idea behind encapsulation is data hiding. There are several reasons why we use encapsulation in object oriented programming. Some of the identified reasons for why we encapsulation are as follows (The real use of encapsulation).
Better maintainability: When all the properties are private and encapsulated, it is easy for us to maintain the program simply by changing the methods.
Make Debugging Easy: This is in line with the above point. We know that the object can only be manipulated through methods. So, this makes it easy to debug and catch bugs.
Have a Controlled Environment: Let the users use the given objects, in a controlled manner, through objects.
Hide Complexities: Hiding the complexities irrelevant to the users. Sometimes, some properties and methods are only for internal use and the user doesn't have to know about these. This makes is simple for the user to use the object.
So, to answer the question, "What is the use of encapsulation when I'm able to change the property values with setter methods?", given above are some of the main reasons why we use encapsulation. To provide an understanding on why, getters and setters are useful, given below are some important points, obtained from this article.
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)
Any how i am able to change the values of fields through setter methods.
Only if the setter method lets you do that.
How we are preventing the accessing fields?
The setter and getter get to control if and how you can access the fields.
A setter may check if the value is valid. It may ask a SecurityManager if you should be allowed to do this. It may convert between data types. And so on.
Lets suppose you make a custom Date class with the following setters / getters:
getDay()
getMonth()
getYear()
setDay()
setMonth()
setYear()
Internally you could store the date using:
private int day;
private int month;
private int year;
Or you could store the date using a java.lang.Date-object:
private Date date;
Encapsulation doesn't expose how your class is working internally. It gives you more freedom to change how your class works. It gives you the option to control the access to your class. You can check if what the user enters is valid (you don't want the user to enter a day with a value of 32).
It's aim is nothing but protecting anything which is prone to change. You have plenty of examples on the web, so I give you some of the advantages of it:
Encapsulated Code is more flexible and easy to change with new requirements
Allows you to control who can access what. (!!!)
Helps to write immutable class in Java
It allows you to change one part of code without affecting other part of code.
Accessing fields thru methods make difference because it makes it OOP. Eg you can extend you class and change the behaviour which you cannot do with direct access. If you have getters / setters you can make a proxy of your class and do some AOP or a make a 1.4 dynamic proxy. You can make a mock from your class and make unit testing...
Encapsultaion is used for hiding the member variables ,by making member as private and access that member variable by getter and setter methods.
Example
class Encapsulation{
private int value ;
Encapsulation() {
System.out.println("constructor calling ");
}
void setValue(int value){
this.value = value;
}
int getValue() {
return value;
}
}
class EncapsulationMain {
public static void main(String args[]) {
Encapsulation obj = new Encapsulation();
obj.setValue(4);
//System.out.print("value is "+obj.value);
//obj.value = 55;
//System.out.print("obj changing the value"+obj.value);
System.out.print("calling the value through the getterMethod"+obj.getValue());
}
}
you cannot access the private value outside the class.
Well, encapsulation is not all about hiding data. It is all about getting control over what is stored in the fields. Using encapsulation we can make a field as read-only or write-only depending upon the requirements.Also the users don't know how the data is stored in the fields. We can use some special encryption in the setter methods and store it in the fields.
For example human is a object. We only require the name field of the human to be read by the user but not to be modified. Then we define only get method on the name field.This is how the encapsulation is useful.
If you have class all of its properties are private-meaning that they cannot be accessed from outside the class- and the only way to interact with class properties is through its public methods.
You are changing tha values by giving the public access to those methods(setters).
using encapsulation the fields of a class can be made read-only or write-only.
Instead of letting everyone access the variables directly:
public Object object;
Is better to use SET and GET methods, or for example just the GET method (Sometimes you dont want nobody to set other value to that variable).
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
By using encapsulation you separate your class from the out-side world (other classes) and out-side world can access and modify your class instance variables through access modifiers, which provides several benefits:
-You can do some logging in your getter/setter methods.
-You can validate /normalize (for example trim spaces, remove special character,...) Your input in setter method.
And also you can hide your implementation from the outside world, for example you have a collection like array list in your class and you write your getter method like this
public List<t> get collection(){
return new ArrayList<t>(this.arrayList);
}
So in this case, in the future if you decide to change your implementation of collection from array list to something else like linked list, you are free to do so because out side world doesn't know anything about your implementation.
Encapsulation is not about secrecy, it is about reducing dependency over separate part of the application.
We control dependency (loose / weak / low coupling) by hiding information over separate part of the application.
Adding to Uche Dim's answer, look at the following example:
Two Connections:
public class Area {
// fields to calculate area
private int length;
private int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getBreadth() {
return breadth;
}
public void setBreadth(int breadth) {
this.breadth = breadth;
}
public int getArea() {
int area = length * breadth;
return area;
}
}
class Main {
public static void main(String[] args) {
Area rectangle = new Area(5, 6);
// Two Connections
int length = rectangle.getLength();
int breadth = rectangle.getBreadth();
int area = length * breadth;
System.out.println("Area: " + area);
}
}
Please note that in the Main class, we are calling two methods (getLength() and getBreadth()) of Area class.
One Connection:
public class Area {
// fields to calculate area
private int length;
private int breadth;
// constructor to initialize values
Area(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getArea() {
int area = length * breadth;
return area;
}
}
class Main {
public static void main(String[] args) {
Area rectangle = new Area(5, 6);
// One Connection
int area = rectangle.getArea();
System.out.println("Area: " + area);
}
}
Here, in the Main class, we are calling one methods (getArea()) of Area class.
So in the second example, the connection is weaker than the previous one (first one calling two methods or the Area class, second one calling one method of the Area class). Given, less connection (lower / weaker coupling) is better, the second example is better.
We should always keep fields and methods private unless necessary. In the Two Connections example, we made the mistake of creating the getters unnecessarily. As we have created it, the IntelliJ Idea (auto suggestion of modern IDE) suggested the developer who was working on the Main class that you can use the getLength() and getBreadth() methods and he did. He did not inquire further to check if there was a getArea() method. As a result he created stronger coupling than necessary.
We should not unnecessarily create getters. We should not unnecessarily make fields public or protected. If you must, first try protected, if that does not work then make it public. That way we will have a lesser possibility of having a tighter coupling.
If you still have the question "what is the difference between making a field public compared to making a field private but it's getters public?", in other words "Why should we use a function to get a value instead of getting it directly?" Well it gives you another layer of abstraction. For example, if you need some extra processing of the data before receiving it (ex. validation), you can do it there. Moreover, once you expose internals of a class, you can not change that internal representation or make it better until making changes in all client codes.
For example, suppose you did something like:
public class Area {
private int length;
private int breadth;
}
class Main {
public static void main(String[] args) {
Area rectangle = new Area(5, 6);
int area = rectangle.length * rectangle.breadth;
System.out.println("Area: " + area);
}
}
Now, if you want to change breadth to width in Area class, you can not do it without breaking the program, unless you search and replace rectangle.breadth with rectangle.width in all the clients where rectangle.breadth was used (in this case Main class).
There are other benefits as well. For example, Member variables cannot be overridden like methods. If a class has getters and setters, it's subclass can override these methods and return what makes more sense in the context of subclass.
Please check Why getter and setter are better than public fields in Java? for more details.
P.S. These are trivial examples, but in large scale, when program grows and frequent change requests are a reality, this makes sense.
I'm OK with using get and set, to mask and make reengineering easier, but if you tell to a novice programmer that using get and set does encapsulation, as I've seen many times, they will use set and get for internal members initialized by the constructor.
And this 99.9 % is wrong!!!!!
private uint8_t myvar = 0;
setMyVar(uint8_t value){
this.myvar = value * (20 / 41);
}
uint8_t getMyVar(){
return this. myvar ;
}
That’s for me is ok, but I think encapsulation is a method first, rather than get and set.
My inglish is not very well,but I think that this article says something like this.
Iam a Java beginner and i would like to ask whats the pros and cons about this:
If i make a Class and i wont write my own setters and getters i can just get and set my class's properties like:
myClassInstance.name = "Jones"
myClassInstance.job = "Manager"
System.out.println(myClassInstance.name);
System.out.println(myClassInstance.job);
Why better if i make getters and setters and do like this:
myClassInstance.setName("Jones");
myClassInstance.setJob("Manager");
System.out.println(myClassInstance.getName());
System.out.println(myClassInstance.getJob());
This question is related to one of the basic principals of OO design: Encapsulation!
Accessors (also known as getters and setters) are methods that let you read and write the value of an instance variable of an object
public class AccessorExample {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
Why to use them?
Getter and Setters make APIs more stable. Lets consider a field public in a class which is accessed by other classes. Now later on, you want to add any extra logic while getting and setting the variable. This will impact the existing client that uses the API. So any changes to this public field will require change to each class that refers it. On the contrary, with accessor methods, one can easily add some logic like cache some data, lazily initialize it later. Moreover, one can fire a property changed event if the new value is different from the previous value. All this will be seamless to the class that gets value using accessor method.
Also Getters and setters methods allow different access levels - for eg. Get may be public, but the Set could be protected.
directly accessing the fields will lead to voilation of encapsulation.
making public variables to access them will be difficult to manage the state of that object.
where as with methods you can easily control state of the object.
Using getters and setters instead of public members is called encapsulation, and is a fundamental OOP concept. This way you are able to control the input and keep some sort of logic and validity to your models.
class Bottle {
public int volume = 0;
}
class EncapsulatedBottle {
private int volume = 0;
public void setVolume(int volume) throws Exception {
if (volume < 1) {
throw new Exception("A bottle cannot have a negative volume");
}
this.volume = volume;
}
public int getVolume() {
return this.volume;
}
}
Spot the difference :-)
Using getters and setters gives you more control over the validity of your objects, giving you the option of testing values that are set to ensure that they are reasonable, etc. (And of course, for read-only properties, you just leave off the setter.) On a modern JVM with a just-in-time compiler, they essentially don't cost anything; if they're really just reading and writing to a private data member, and if they're in a hotspot (bit of code that gets used a lot), the JIT will inline them.
Using getters/setters is normally better, because:
you can restrict (public) access to readonly (no setter)
you can add additional code without having to recompile/change the users of the property (i.e. classes that call the getter/setter)
it complies with the Java Bean specification which states a property must have getters/setters - and many libraries/frameworks, like Java EL etc. rely on that contract
Hey there, I'm trying to call a method in a subclass, savingsaccount. when i call this method, it involves a field called balance in the superclass, called account. When i try to involve this field in the method, it says that the field is private and cannot be accessed. Is there a way around this with keeping the field private? We are not supposed to change the access type.
Kind regards and much appreciation for any help
No. The superclass should provide appropriate methods to access the field's value appropriately, possibly performing validation.
The whole point of making a field private is to stop other classes from accessing it directly - instead they have to go through the methods you expose.
Add a protected getter method in the superclass to return the balance value, such as this:
protected double getBalance() {
return this.balance;
}
This method will be visible to subclasses but not visible externally. It allows you also to keep the balance field private.
If it's private you can't get at it, that's it. The author of the superclass has the responsibility to make their class open to extension. If they chose not to allow this kind of extension then there's nothing to be done.
Now check, did they provide accessor methods, or anticipate your need for extension in some other way? If you can talk to the author ask them whether they considered this need.
private means that the variable is private to that class. protected would mean that subclasses can access it and public means anyone can see it. If you can't change the access type then you should provide an accessor method in the super-class:
public double getBalance() {
return balance;
}
In the sublclass you can then see the balance by calling getBalance
use reflection.
hey, I'm just answering the question as is.
As my name suggests, I am a .NET developer but I have a growing interest in Java, and I am interested in learning more about other languages as this helps me to learn more about programming generally.
Anyway, my question is this: Methods which don't take parameters/work with state (which is just parameters in the method, correct me if I am wrong) are recommended to be made static. What is the relationship/link between static and parameterless methods? Not working with state means if you pass a Person object into the method, and you don't edit that object's state (Eg its properties) - this is my understanding.
I don't mind any Java specific answers.
Thanks
"What is the relationship/link between static and parameterless methods? "
None.
"Methods which don't take parameters/work with state... are recommended to be made static"
Really? By whom? Can you provide a link or quote?
Static means that the method belongs to the class -- as a whole -- not any specific object of that class. Therefore, static methods can only deal with static variables, not instance variables.
Parameterless doesn't mean anything. It may be that the method deals only with instance variables or only with static variables. Or it returns a constant. Or it has some calculation which is private to that method. It could, for example, create a socket, do a read using HTTP, and destroy the socket. No parameters; no instance variables.
There is no relationship between static and parameterless methods.
A static method is one which does not access instance state in the receiving class (and therefore does not need to be associated with a particular instance). It can easily take parameters:
public class Calculator
{
public static int Add(int a, int b) { return a + b; } // does not need any Calculator state
}
A static method can access its parameters (and can therefore modify their state if they allow it):
public class Officialdom
{
public static void Rename(Person person) { person.Name = "Bob"; } // does not need any Officialdom state
}
Conversely, a parameterless method might well need to access receiver state, and therefore be an instance (non-static) method:
public class Spline
{
private bool _isReticulated;
public void Reticulate()
{
_isReticulated = true; // does need Spline state
}
}
(I've posted code samples in C# because this is language-independent; the same notions and distinctions apply in Java, possibly with a few keyword changes.)
there is no connection between static methods and what they do with parameters passed into them. static methods are CLASS level methods and not INSTANCE level in Java. static methods are associated with the Class they are declared in and not instances of those classes.
There's a general principle that methods should not have access to more data than they need. This is one of the reasons why member variables are usually private and OO uses encapsulation to hide data and code from other parts of the system.
When you have a function which does not require access to the variables in that class, some people recommend making the method static.
Whether or not a function has parameters does not affect whether it has access to instance methods.