Is there any purpose to make private class variable to public - java

Hello I am curious to know that Is there any purpose to make private class variable to public in Java.
public class XYZ {
public String ID;
public ABC abc;
private class ABC {
public boolean isExist;
}
}
Thanks in advance.

Yes, there's a purpose. If you do that then those program elements which can access the class can manipulate that variable directly. Otherwise (say if the variable is private), those elements would still be able to access the class but won't be able to manipulate the variable (unless you provide a getter/setter for it).
Think about it this way: the class modifier defines the level of access to the class, the variable modifier then defines the level of access to the variable itself (for those elements which can access the class).

This is sometimes done for data-only classes. For example, this is sometimes done to represent the models stored in databases (see Objectify for a real example of how this is used, in conjunction with annotations, to represent the database models that are stored in an App Engine database).
That being said, this sort of thing makes for a very poor API. If you do this, I'd suggest doing it with classes that are either package-level access or in private nested classes, only. When exposing functionality or data to code outside your package, it is generally better to do it with a carefully designed interface that would allow you to change the implementation if your underlying structure were to change.

That is to make isExist visible to XYZ class.
Note, ABC is only visible to XYZ and not to any outside classes and its variable is public so you can have access to it. private has not meaning to XYZ, only outside classes
From inside XYZ,
ABC abc = new ABC(); //can only be accessed by XYZ.
abc.isExists = true; //can only be accessed by XYZ
Making isExist public means you do not care about encapsulating (prevent it from unwanted manipulation from outside) it. If you make it private, you will need a get accessor to expose it
private class ABC {
private boolean _isExist; //only through accessors
public boolean isExist()
{
return _isExist;
}
}

You can do either of the following two things to your class instance variables:
THING # 1: Keep your instance variables private. Then have public getter and setter methods to get and set the value of that variable. The good thing about it is that you get to put checks inside the setter method. For example, lengths can never be negative. So, you can't just make lengths public and let anyone assign it whatever value they want. You need to make sure the value being assigned to it is not negative. So:
class myClass {
private int length;
public void setLength(int i) {
if ( i > 0 ) {
length = i;
}
}
}
Also, you can make your instance variables read-only, write-only, or read-and-write, depending on the availability of getter and setter methods for that private variable.
THING # 2 : If you don't need any restrictions on the value of your instance variable, and you want it to neither be read-only nor write-only, then it's fine to keep that variable public. For example: babies can have any name - no restrictions:
class Baby {
public name;
}
class Mother {
public void nameTheBaby() {
Baby baby = new Baby();
baby.name = "Sarah";
}
}

Related

What is the advantage of having a private attribute with getters and setters? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 9 years ago.
In object oriented programming, I used to have this question and I still do :
What would be the benefit of declaring a class member as private if we
will create for it a public getter and a public setter?
I don't see any difference at the security level between the case above and the case of declaring the class member as public.
Thanks!
Encapsulation provides data hiding and more control on the member variables. If an attribute is public then anyone can access it and can assign any value to it. But if your member variable is private and you have provided a setter for it. Then you always have an option to put some constraints check in the setter method to avoid setting an illogical value.
For example a class with public member only :
class MyClass {
public int age;
}
public MyClassUser {
public static void main(String args[]) {
MyClass obj = new MyClass();
obj.age = -5 // not a logical value for age
}
}
Same class with private member and a setter:
class MyClass {
private int age;
public void setAge(int age) {
if(age < 0) {
// do not use input value and use default
} else {
this.age = age;
}
}
}
If your class has no invariants to maintain then writing public getters and setters for a private data member is pointless; you should just use a public data member.
On the other hand, if you do have invariants to maintain then using a setter can allow you to restrict the values that can be assigned to the data member.
Note that just because you have a data member doesn't mean you have to write any getters or setters for it.
Pet peeve: "but what if the internals change?" It doesn't matter. You had a getName function that returned a std::string const&. Getters reduce encapsulation because they constrain your choices when changing the implementation later on.
Quick (and a bit silly) example:
class Foo {
private int age = -1; // unset value
public setAge(int a) {
if (a < 0) {
throw new IllegalArgumentException("Invalid age "+a);
}
age = a;
}
public getAge() {
if (age < 0) {
throw new InvalidStateException("Age was not previously set.")
}
return age;
}
}
In short: you gain control and you can assure values are correct. It's called encapsulation.
http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29
You could later change the internal representation of the class member, add functionality to the getter and setter (such as notifying an Observer), all without changing the interface (the public getter and setter).
Your question is indeed the difference between Fields and Properties. Fileds are usually private and properties do expose them. Bellow is a quote of a brilliant answer on SO:
Properties expose fields. Fields should (almost always) be kept
private to a class and accessed via get and set properties. Properties
provide a level of abstraction allowing you to change the fields while
not affecting the external way they are accessed by the things that
use your class.
What is the difference between a Field and a Property in C#?
In C# automatic properties will create a filed for you without having to manually declare it:
public Prop { get; set; }
public Prop { public get; private set; }
public Prop { private get; public set; }
// etc, you can specify access modifier as per your need
I don't see any difference at the security level between the case above and the case of declaring the class member as public.
Immediate question are :
1)What if you want to check some conditions,While setting the value ?
2)What if the subclassess want to return or set something else,by ovveridng that method ?
Other reason:Why getter and setter are better than public fields in Java
If you have a data transfer object, with limited scope and by design it should have no logic associated with it, I don't see a value in getters and setters.
However, if you have a component which may or may not have some logic associated with it or it could be widely used, then it makes sense to hide the details of how the data is stored. Initially it might appear that all the getters and setters are trivial and just fill up you class, but over time you might add validation to the setters and even change the getters. e.g. you might drop a field (and return a constant in future), store the data in a delegated object or compute the value from other fields.
Beside the encapsulation, consider a situation where your setter is not simply sets a value.
What if you're using it in many classes? And now you realize you want to change the functionality of it? You'll have to change it in whole places where you manually set it. Whereas if you had a setter life would have been easier.
As with any encapsulation: it hides implementation details. This allows you to control access and provide a stable interface even when the internals change.
Setter controlling access
class Person //version 1.0
{
std::string name;
public:
std::string getName() const { return name; }
void setName(const std::string &newName)
{
if (!newName.empty()) //disallow empty names
name = newName;
}
};
Getter useful during API evolution
class Person //version 1.1
{
std::string firstName;
std::string lastName;
public:
std::string getFirstName() const { return firstName; }
void setFirstName(const std::string &newFirstName)
{
firstName = newFirstName;
}
std::string getLastName() const { return lastName; }
void setLastName(const std::string &newLastName)
{
if (!newLastName.empty()) //disallow empty last names
firstName = newFirstName;
}
std::string getName() const
{
std::ostringstream s;
if (!firstName.empty())
s << fistName << ' ';
s << lastName;
return s.str();
}
void setName(const std::string &newName)
{
setFirstName(splitUntilLastSpace(newName));
setLastName(splitFromLastSpace(newName));
}
};
Accessor methods provide a single point of update for a given field. This is beneficial because validation logic or other modifications to the field can be controlled via the single method as opposed to having the field directly accessed throughout the code base.
See this IBM document which details more benefits: http://www.ibm.com/developerworks/java/library/ws-tip-why.html
If the public getter and public setter are just to return the value of the private property and to change its value, then I see no difference.
However, you are implementing encapsulation, so in a later moment you can implement a different behavior, including argument check for setter or write-only/read-only properties, for instance.
Actually, if you're developping alone on a small project and you won't reuse your code, it's kinda useless, but it's mostly a good habbit.
But, in team developpment, you may need to have some control on modification, and you can do it through the getters and setters.
Moreover, in some classes, you'll only have getters, as the setters will be done by the constructor, or via some other functions.
Declaring variables as private is called as Encapsulation in Java.
Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:
Encapsulated Code is more flexible and easy to change with new requirements.
Encapsulation in Java makes unit testing easy.
Encapsulation in Java allows you to control who can access what.
Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading
environment.
Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing
are encapsulated in one place.
Encapsulation allows you to change one part of code without affecting other part of code.
one more advantage is
Making variables private in java and providing getter and setter for them makes your class compatible Java bean naming convention
I have only one thing to add to the excellent answers that this post have so far.
Sometimes a class attribute could have more than one Getter or Setter, let's illustrate with a silly short example:
class Angle
{
public:
void Set(MyAngleTypedef a_value) { m_angle = a_value; }
// Note the 'Radians' type
void SetRadians(Radians a_value) { m_angle = ConvertRadiansToOurUnit(a_value); }
// Note the 'Degrees' type
void SetDegrees(Degrees a_value) { m_angle = ConvertDegreesToOurUnit(a_value); }
void Get(MyAngleTypedef a_value) const { return m_angle; }
// Note the 'Radians' type
Radians GetRadians(Radians a_value) const { return ConvertOurUnitToRadians(m_angle); }
// Note the 'Degrees' type
Degrees GetDegrees(Degrees a_value) const { return ConvertOurUnitToDegrees(m_angle); }
private:
// Raw value of the angle in some user-defined scale.
MyAngleTypedef m_angle;
}
Is meaningless to store the value more than once for each unit type which you want to work, so the Getters and Setters will provide an interface that makes the class able to work with different units.
IMHO, when a object contains active attributes (attributes that must do some work after or before it is assigned or accessed) it must be a class with only the essential Getters and Setters (the private attributes that doesn't need accessed outside the class, obviously doesn't need public Getters and Setters).
In the other hand if an object conains only passive attributes (attributes that doesn't need extra work when assigned or accessed) it must be a struct and therefore all his attributes would be public accesible without Getters and Setters.
Note that this answer is from the c++ point of view, check this question for more information.
One of the most important concepts of Object Oriented Programming is encapsulation. You encapsulate data and the methods that act on that data together. Ideally, data should be accessed only via its related methods. And the state of data should be "queried" by other objects via these methods. Making a variable public will result in that variable being directly available to all other objects breaking encapsulation.

In which situations we make variables as public and methods as private?

Currently I am learning basics of java and C++. I have read in book Let Us C++, that in almost every case we we make instance variables private and methods public for the security purposes. But it is also mentioned in this book that in some cases we make variables public and methods private..
I am continuously thinking, in which cases we will do so. Can anyone please explain this.
Private methods (or private member functions in C++ terminology) are mostly useful as helper functions. For example, think of the case that you want to implement fractions, but want to ensure that your fraction is always normalized. Then you could use a private member function normalize() which normalizes your fraction, and which is called after each operation which might result in a non-normalized fraction, for example (C++ code):
class Fraction
{
public:
Fraction(int num, int den = 1);
Fraction operator+=(Fraction const& other);
Fraction operator*=(Fraction const& other);
// ...
private:
int numerator, denominator;
};
Fraction::Fraction(int num, int den):
numerator(num),
denominator(den)
{
normalize();
}
Fraction Fraction::operator+=(Fraction const& other)
{
int new_den = denominator*other.denominator;
numerator = numerator*other.denominator + denominator*other.numerator;
denominator = new_den;
}
Fraction Fraction::operator*=(Fraction const& other)
{
numerator *= other.numerator;
denominator *= other.denominator;
normalize();
}
void Fraction::normalize()
{
int factor = gcd(numerator, denominator);
numerator /= factor;
denominator /= factor;
}
Another, C++ specific use of private functions is based on the fact that in C++ private is only about access control, not about visibility. This enables to do unoverridable pre-post-condition checking in the base class while making the actual function virtual:
class Base
{
public:
foo frobnicate(some arguments);
private:
virtual foo do_frobnicate(some arguments) = 0;
};
foo Base::frobnicate(some arguments)
{
check_precondition(arguments);
foo result = do_frobnicate(arguments);
check_post_condition(foo);
return foo;
}
Classes derived from Base will override do_frobnicate, while users will call frobnicate which always checks the pre/postconditions no matter what the derived class does.
Generally static final variables are public in a class. If you don't need to change the value of that variable and want other classes to access it then you make it public static final.
Private methods are used only within the class for doing the task, which is internal to that class. Like a utility method or some business calculation method. Or simply to break the code of public method into multiple private methods, so that methods don't grow too big.
When a method is to be used by other methods(public) of the class and you do not want the object to access that method directly, we make that method as private.
And in some cases, if you want to access your variable directly from the class object, then make it public.
If you don't need the varibale or methode in other classes don't make it public. This goes for methodes and variables.
private methods are for the internal use of the class. They can be called from other public classes. Those are private because you encapsualted from outer world.
For example
public void method1(){
method2();
}
private void method2(){
// for internal use
}
Public variables are mainly used for class variables in which cases there is no harm of direct accessing the variables from outside. For example
public static final int FLAG = true;
You can directly call the variable from outside.
It depends how much security you want for each class.
For example, if you have a Vector class, that only has 3 variables x, y and z, you should make them public. Many classes will probably use the Vector class and it's fine if they change values in it.
If you have a Person class that stores credit card number, background record, address etc, you should make them private to avoid security issues.
However, if you have all variables as private, and you provide accessors and mutators for all of them, you're effectively making them just like public (but with more work).
EDIT:
All constant variables should be public, because you cannot change them anyway.
Static variables could be both, depending on a situation. Probably better to have static get and set functions for static variables.
Private variables or functions can be use only in the class where they are declarated.
Public variables or functions can be use everywhere in your application.
So you should declarate private all those variables and functions that you are going to use ONLY in the class where they belong.
Example:
public class Car {
private String model;
public setModel(String model) {
if (model != null)
this.model = model;
}
public getModel() {
return model;
}
private doSomething() {
model = "Ford";
}
}
In the class Car we declarate the String model as private because we are going to use it only in the class Car, doing this we assure that other classes couldn't change the value of this String without using the function setModel.
The functions setModel and getModel are public, so we can access the private variable model from other classes ONLY using those methods.
In this example, the function setModel checks if the value its null, in which case it doesn't set the value. Here you can see that if you had declarated the String model as public, you wouldn't have control over what value it's being recorded.
The function doSomething is private and other classes can't use it. For other side, like this function is private and it belong to the same class where is the String model, it can change its value without using the method setModel.
A rule of thumb, you make methods public when it is okay for other classes to access them. internal methods or helper methods should either be protected or private.Protected if you want the method to be extendable by those extending your class however if you don't want this just mark them private.

Protected methods in Java

Why do we need protected modifier methods when we can directly set the variable to protected?
For e.g: In the below code, they set the instance variable SocialSecurityNumber to private and define a protected setter method to set its value? Why can't we directly set the variable SocialSecurityNumber to protected?
public class SSNWrapper {
private int SocialSecurityNumber ;
public SSNWrapper (int ssn) { socialSecurityNumber = ssn ;}
public int getSSN () { return SocialSecurityNumber; }
protected void setSSN(int SSN) { socialSecuritynumber = ssn ; }
}
In that specific example, there would not be much difference. In real life, the setSSN method should probably be more like:
protected void setSSN(int SSN) throws InvalidSSNException {
// check that the given SSN is valid
// ...
socialSecurityNumber = ssn;
}
This allows the base class to guarantee that it only holds valid SSNs. The base class cannot guarantee that if the field is protected.
From the tutorial on Access modifiers:
Tips on Choosing an Access Level:
If other programmers use your class, you want to ensure that errors
from misuse cannot happen. Access levels can help you do this.
Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
Avoid public fields except for constants. (Many of the examples in the
tutorial use public fields. This may help to illustrate some points
concisely, but is not recommended for production code.) Public fields
tend to link you to a particular implementation and limit your
flexibility in changing your code.
The short version is it prevents other classes from modifying the data within the class that declares the instance variable private.
Because sometimes you need to change operation which get or set this value. For example you need to calculate this value. Or set another value. Or run listener or something.... So this is to give you more flexibility.

Why am I able to call private method?

I should not be able to invoke a private method of an instantiated object. I wonder why the code below works.
public class SimpleApp2 {
/**
* #param args
*/
private int var1;
public static void main(String[] args) {
SimpleApp2 s = new SimpleApp2();
s.method1(); // interesting?!
}
private void method1() {
System.out.println("this is method1");
this.method2(); // this is ok
SimpleApp2 s2 = new SimpleApp2();
s2.method2(); // interesting?!
System.out.println(s2.var1); // interesting?!
}
private void method2() {
this.var1 = 10;
System.out.println("this is method2");
}
}
I understand that a private method is accessible from within the class. But if a method inside a class instantiate an object of that same class, shouldn't the scope rules apply to that instantiated object?
Can static method like main access the non-static member of the class, as given in this example ?
Your main method is a method of SimpleApp, so it can call SimpleApp's private methods.
Just because it's a static method doesn't prevent it behaving like a method for the purposes of public, private etc. private only prevents methods of other classes from accessing SimpleApp's methods.
Because main is also a member of SimpleApp.
See below chart
Access Modifiers
**Same Class Same Package Subclass Other packages**
**public** Y Y Y Y
**protected** Y Y Y N
**no access modifier** Y Y N N
**private** Y N N N
As your method is inside car it's accessible based on above thumb rule.
From the Java Tutorial:
private modifier—the field is accessible only within its own class
The main method is inside the same class as the private method and thus has access to it.
private means "only stuff in this class can mess around with it". It doesn't mean "only this instance can call its methods", which seems to be what you're expecting. Any code in SimpleApp can use anything in any SimpleApp. The alternative would be to break encapsulation -- how would you make a proper equals method, for example, that didn't require access to another instance's fields, without making those fields protected or even public or requiring getters for data that should only be available inside the class?
The call you issue is from within the same class where your private method resides. This is allowed. This is the way 'private' is defined in java.
In the program, we created two instances of the class by using which we called two private methods. It's a kind of interesting to see this works is that this is the way we used to call public or default methods outside its class using object reference. In this case, it's all done inside the class definition, so it's valid. The same code put outside the class will result in error.
Because the private scope limits access to the class defining the method, and your main happens to be in the same class.
private modifier—the field is accessible only within its own class.
See Access Modifiers in the Java Documentation.

Accesing a method from another class file?

I need to acces a variable (an int) from another class file. How would I do this? It's a public int, I need to get the int value and put it into a file.
If you have an instance:
AnotherClass another = new AnotherClass();
Then if the field (instance variable) is public:
another.someField;
or if you have a getter method
another.getSomeField();
If none of these is true - add a getter method (this is the preferred way to access instance variables).
If you can't change the class - as a last resort you can use reflection.
Example:
MyClass myclass = new MyClass();
System.out.print(myclass.myint)
Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:
public class Main{
int variableName;
public int getVariableName(){
return this.variableName;
}
public setVariableName(int variableName){
this.variableName = variableName;
}
}
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:
Main m = new Main();
int a = m.getVariableName();
Hope it helps.
If you have an instance of that other class, you access it as {instance}.varable.
That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.
If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.
Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.
Basically, in the other class, do this:
public int Number
{
get
{
return number;
}
set
{
number = value;
}
}
private int number;
Doing this allows you to easily set that in to something else if you need to or to get it's current value. To do this, create an instance of the "AnotherClass" as Bozho already explained.

Categories

Resources