Why is private member of a class accessible in compareTo? [duplicate] - java

This question already has answers here:
Do objects encapsulate data so that not even other instances of the same class can access the data?
(7 answers)
Closed 8 years ago.
I wrote the following class to fiddle around with Comparable/Serializable interfaces.
package testpro;
public class SerialTest implements Comparable {
private int circleSize = 10;
private int getCircleSize() {
return circleSize;
}
#Override
public int compareTo(Object o) {
SerialTest object = (SerialTest) o;
if(getCircleSize()>object.getCircleSize()){ // I can access object.getCircleSize() here, but it's private.. why?
return 1;
}
else if(getCircleSize()<object.getCircleSize()){// I can access object.getCircleSize() here, but it's private.. why?
return -1;
}
else{
return 0;
}
}
}
I'm passing an Object o to compareTo() method, but getCircleSize() is private. So how is that possible, that I've got an access to this?
I'm pretty sure C++ wouldn't let it go.

Private means accessible from the same class only. And you are in the same class, after casting Object o to SerialTest object.

Private method are accessible within the class itself. Since both methods residing the same class, there no problem of accessing it.
The private modifier specifies that the member can only be accessed in
its own class.
Check here for more details

private are not accessible by other classes. But within the class it is accessible for programming. Such as your code, you can use all the private identifiers or methods within the class while generating a result.
C++ also provides this function. You can easily use private method inside a class or method, to generate a response for a function call. It is simple and is legal!

You access to private member from same class. You override method compareTo() and in it you are accessed to your private member.
You can't do this with private member without accessor from each other class.
You can learn this from this link.

Related

Accessing private variables inside the method [duplicate]

How is the compiler not complaining when I write the following code?
public class MyClass
{
private int count;
public MyClass(int x){
this.count=x;
}
public void testPrivate(MyClass o){
System.out.println(o.count);
}
}
Even though it is an instance of the same class in which testPrivate is written, shouldn't it give a compilation error at System.out.println(o.count)? After all, I am trying to access a private variable directly.
The code even runs fine.
A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own (this) instance's private member or some other instance's private member.
This is stated in JLS 6.6.1:
...Otherwise, if the member or constructor is declared private, then 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.
This feature of Java allows you to write methods that accept an instance of the class as an argument (for example - clone(Object other), compareTo(Object other)) without relying on the class having non private getters for all the private properties that need to be accessed.
Private fields are private to the class as a whole, not just to the object.
Other classes do not know that MyClass has a field called count; however, A MyClass object knows that another MyClass object has the count field.
Accessors are not security! They are encapsulation, to keep others from having to know about the code.
Consider if someone wrote a Quantum Bogo Sort, but disappeared once he quashed the last bug -- understanding the code causes one to be either deleted from the universe or to go mad.
Despite this minor drawback, if properly encapsulated, this should become your prefered sorting algorithm, as all fields and methods except Sort should be private.
You don't know how it works, and you don't want to know how it works, but it works and that's enough. If on the other hand, everything is public, and you have to understand how it does what it does to use it correctly -- that's just too much bother, I'll stick with quicksort.
Though it is the instance of the same class in which testPrivate is
written, but shouldn't it through a compiler error at
System.out.println(o.count);
No. It will never throw a compilation error.
This is much similar to what a simple getter and setter does or a copy constructor does. Remember we can access private members using this.
public MyClass {
private String propertyOne;
private String propertyTwo;
// cannot access otherObject private members directly
// so we use getters
// But MyClass private members are accessible using this.
public MyClass(OtherClass otherObject) {
this.propertyOne = otherObject.getPropertyOne();
this.propertyTwo = otherObject.calculatePropertyTwo();
}
public void setPropertyOne(String propertyOne) {
this.propertyOne = propertyOne;
}
public String getPropertyOne() {
return this.propertyOne;
}
}
Your testPrivate method accepts an instance of MyClass. Since testPrivate is a method inside MyClass, it will have access to private properties.
public void testPrivate(MyClass o) {
this.propertyOne = o.propertOne;
}
Methods defined inside the class will always have access to it's private members, through this. and instance variable.
But if you define testPrivate outside of MyClass then, you won't have access to private members. There you will have to use a method or a setter or a getter.
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Check the official documentation

Understanding private fields in java [duplicate]

How is the compiler not complaining when I write the following code?
public class MyClass
{
private int count;
public MyClass(int x){
this.count=x;
}
public void testPrivate(MyClass o){
System.out.println(o.count);
}
}
Even though it is an instance of the same class in which testPrivate is written, shouldn't it give a compilation error at System.out.println(o.count)? After all, I am trying to access a private variable directly.
The code even runs fine.
A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own (this) instance's private member or some other instance's private member.
This is stated in JLS 6.6.1:
...Otherwise, if the member or constructor is declared private, then 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.
This feature of Java allows you to write methods that accept an instance of the class as an argument (for example - clone(Object other), compareTo(Object other)) without relying on the class having non private getters for all the private properties that need to be accessed.
Private fields are private to the class as a whole, not just to the object.
Other classes do not know that MyClass has a field called count; however, A MyClass object knows that another MyClass object has the count field.
Accessors are not security! They are encapsulation, to keep others from having to know about the code.
Consider if someone wrote a Quantum Bogo Sort, but disappeared once he quashed the last bug -- understanding the code causes one to be either deleted from the universe or to go mad.
Despite this minor drawback, if properly encapsulated, this should become your prefered sorting algorithm, as all fields and methods except Sort should be private.
You don't know how it works, and you don't want to know how it works, but it works and that's enough. If on the other hand, everything is public, and you have to understand how it does what it does to use it correctly -- that's just too much bother, I'll stick with quicksort.
Though it is the instance of the same class in which testPrivate is
written, but shouldn't it through a compiler error at
System.out.println(o.count);
No. It will never throw a compilation error.
This is much similar to what a simple getter and setter does or a copy constructor does. Remember we can access private members using this.
public MyClass {
private String propertyOne;
private String propertyTwo;
// cannot access otherObject private members directly
// so we use getters
// But MyClass private members are accessible using this.
public MyClass(OtherClass otherObject) {
this.propertyOne = otherObject.getPropertyOne();
this.propertyTwo = otherObject.calculatePropertyTwo();
}
public void setPropertyOne(String propertyOne) {
this.propertyOne = propertyOne;
}
public String getPropertyOne() {
return this.propertyOne;
}
}
Your testPrivate method accepts an instance of MyClass. Since testPrivate is a method inside MyClass, it will have access to private properties.
public void testPrivate(MyClass o) {
this.propertyOne = o.propertOne;
}
Methods defined inside the class will always have access to it's private members, through this. and instance variable.
But if you define testPrivate outside of MyClass then, you won't have access to private members. There you will have to use a method or a setter or a getter.
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Check the official documentation

Java private member: why does this compile? [duplicate]

How is the compiler not complaining when I write the following code?
public class MyClass
{
private int count;
public MyClass(int x){
this.count=x;
}
public void testPrivate(MyClass o){
System.out.println(o.count);
}
}
Even though it is an instance of the same class in which testPrivate is written, shouldn't it give a compilation error at System.out.println(o.count)? After all, I am trying to access a private variable directly.
The code even runs fine.
A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own (this) instance's private member or some other instance's private member.
This is stated in JLS 6.6.1:
...Otherwise, if the member or constructor is declared private, then 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.
This feature of Java allows you to write methods that accept an instance of the class as an argument (for example - clone(Object other), compareTo(Object other)) without relying on the class having non private getters for all the private properties that need to be accessed.
Private fields are private to the class as a whole, not just to the object.
Other classes do not know that MyClass has a field called count; however, A MyClass object knows that another MyClass object has the count field.
Accessors are not security! They are encapsulation, to keep others from having to know about the code.
Consider if someone wrote a Quantum Bogo Sort, but disappeared once he quashed the last bug -- understanding the code causes one to be either deleted from the universe or to go mad.
Despite this minor drawback, if properly encapsulated, this should become your prefered sorting algorithm, as all fields and methods except Sort should be private.
You don't know how it works, and you don't want to know how it works, but it works and that's enough. If on the other hand, everything is public, and you have to understand how it does what it does to use it correctly -- that's just too much bother, I'll stick with quicksort.
Though it is the instance of the same class in which testPrivate is
written, but shouldn't it through a compiler error at
System.out.println(o.count);
No. It will never throw a compilation error.
This is much similar to what a simple getter and setter does or a copy constructor does. Remember we can access private members using this.
public MyClass {
private String propertyOne;
private String propertyTwo;
// cannot access otherObject private members directly
// so we use getters
// But MyClass private members are accessible using this.
public MyClass(OtherClass otherObject) {
this.propertyOne = otherObject.getPropertyOne();
this.propertyTwo = otherObject.calculatePropertyTwo();
}
public void setPropertyOne(String propertyOne) {
this.propertyOne = propertyOne;
}
public String getPropertyOne() {
return this.propertyOne;
}
}
Your testPrivate method accepts an instance of MyClass. Since testPrivate is a method inside MyClass, it will have access to private properties.
public void testPrivate(MyClass o) {
this.propertyOne = o.propertOne;
}
Methods defined inside the class will always have access to it's private members, through this. and instance variable.
But if you define testPrivate outside of MyClass then, you won't have access to private members. There you will have to use a method or a setter or a getter.
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Check the official documentation

How can I create an utility class? [duplicate]

This question already has answers here:
Java: Static Class?
(8 answers)
Closed 8 years ago.
I want to create a class with utility methods, for example
public class Util {
public static void f (int i) {...}
public static int g (int i, int j) {...}
}
Which is the best method to create an utility class?
Should I use a private constructor?
Should I make the utility class for abstract class?
Should I do nothing?
For a completely stateless utility class in Java, I suggest the class be declared public and final, and have a private constructor to prevent instantiation. The final keyword prevents sub-classing and can improve efficiency at runtime.
The class should contain all static methods and should not be declared abstract (as that would imply the class is not concrete and has to be implemented in some way).
The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).
The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).
Methods in the class should have appropriate names.
Methods only used by the class itself should be private.
The class should not have any non-final/non-static class fields.
The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).
Example:
public final class ExampleUtilities {
// Example Utility method
public static int foo(int i, int j) {
int val;
//Do stuff
return val;
}
// Example Utility method overloaded
public static float foo(float i, float j) {
float val;
//Do stuff
return val;
}
// Example Utility method calling private method
public static long bar(int p) {
return hid(p) * hid(p);
}
// Example private method
private static long hid(int i) {
return i * 2 + 1;
}
}
Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.
According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.
Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.
I would make the class final and every method would be static.
So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)
Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.
Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

Can java private data members be accessed from outside the class? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it possible in Java to access private fields via reflection
Is there any way so that we can call the private data members of a class in java, can be accessed outside the class.
I want this for a tricky question banks.
As much my java experience i think this is possible, but i don't know how to do it.
1) You can do it with reflection, if SecurityManager allows
class B {
private int x = 2;
}
public class A {
public static void main(String[] args) throws Exception {
Field f = B.class.getDeclaredField("x");
f.setAccessible(true);
f.get(new B());
}
}
2) in case of inner classes
class A {
private int a = 1;
class B {
private int b = 2;
private void xxx() {
int i = new A().a;
};
}
private void aaa() {
int i = new B().b;
}
As per the java language specification, 3rd edition:
6.6.8 Example: private Fields, Methods, and Constructors
A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.
You can use reflection in java to access private fields. Ideally, you should be using public setters and getter methods to access such data from outside the class (as others have posted)
for more info about access modifiers check below link
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
and this for Accessing private variables in Java via reflection
Accessing private variables in Java via reflection
No private member can't be used outside the class
You can use getter and setter methods for this purpose
You can do it using public methods that returns/set the private field value.
public Class A{
private String myData;
public String getMyData(){
return myData;
}
public void setMyData(String data){
this.myData=data;
}
}
Define a public get method to get private field of your class.
No you cannot, by any means access the private variables in java.
You can provide public getter and setter methods to access or change the value of the private member variables.

Categories

Resources