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

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.

Related

In Java, why are the private data members accessible outside the class if written like this? [duplicate]

This question already has answers here:
Why can an instance of a class access private fields of another instance of its own type?
(3 answers)
Closed 1 year ago.
Usually, if type is a private member of a class named Pass, and obj is a reference to object of Pass class, we cannot do obj.type because type is private member so that would give error.
In copy() method, a is passed as a parameter where a is a reference to Pass object.
By the same logic, we should also not be allowed to do a.type.
But this code runs fine. Why? This is my doubt.
public class Main {
public static void main(String[] args) {
Pass ob1 = new Pass(10,'c');
Pass ob2 = new Pass(20,'f');
ob1.print();
ob2.print();
ob1.copy(ob2);
ob1.print();
ob2.print();
}
}
class Pass {
private int number = 0;
private char type = 'a';
public Pass(int i, char t) {
this.number = i;
this.type = t;
}
public void copy(Pass a) {
this.number = a.number;
this.type = a.type;
}
public void print() {
System.out.println(number + " =>" + type);
}
}
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package, and outside the package.
In your case, you access the type variable inside the Pass class. So even though it is a private variable, you have permission to access it.
Because the method is in the same class, it can access private members of other instances. private only means that only functions in the class can access it, with no restrictions on which object is doing the accessing.

Private members and inheritance [duplicate]

This question already has answers here:
Do subclasses inherit private fields?
(21 answers)
Closed 8 years ago.
I've read in a textbook that class members that are marked as private are not inherited.
So I thought if class A has a private variable x and class B would extend class A then there would be no variable x in class B.
However a following example shows that I misunderstood that:
public class testdrive
{
public static void main(String[] args) {
B b = new B();
b.setLength(32);
System.out.print(b.getLength());
}
}
class A {
private int length;
public void setLength(int len) {
length = len;
}
public int getLength() {
return length;
}
}
class B extends A {
public void dummy() {
}
}
The result is 32 and I'm confused because it looks like object with ref b now has the variable length and it's value is 32. But ref b refers to object created from class B where the length variable is not defined.
So what's the truth, does class B inherit the private variable length? If so, what does it mean that private variables are not inherited?
The field that is private is hidden in B. But, your public methods are inherited and are accessible, and they can access the private field.
Hey man it's not how you think it is, private fields can only be accessed by the methods present in the same class (given ofcourse that the methods are accessible from other class)
its not that you can directly call:
b.length=8;
Or you cannot even do this:(write this where you created the object for B)
A a = new A();
a.length=8;
both of these approach are invalid!
For more info:
you don't even need to extend B from A, just create an object of A in main and use those get and set methods of yours and it will work too!
You don't have direct access to the private fields and method of a superclass but you are able to access them through the use of other public methods.
This is one of the fundamental concepts of the Object-Oriented Programming and it's named Encapsulation.
Read more about this here : TutorialsPoint.
Bottom-line : You can't directly access a private field or method like this
b.length = 32;
nor like this (for the superclass)
A a = new A();
a.length = 32;
but you can manipulate those fields through the use of a public method like in your example.
The reason is simple : your private fields/methods are hidden for other classes except for the class which holds them , but your public fields/methods are not hidden.

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

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.

Implement a final class without the "final" keyword

A friend of mine was asked that question in his on-phone job interview a couple of days a go.
I don't have a clue. can anyone suggest a solution?
(His job interview is over. just out of curiosity now )
10x.
Mark constructor as private
Provide a static method on the class to create instance of a class. This will allow you to instantiate objects of that class
I don't know what they mean exactly mean by a final class. If they mean a class that cannot be extended by inheritence, than clearly this cannot be done, except by marking that class with final (or sealed, or whatever the language keyword is).
But if the mean final as in immutable, such that a derived class can't modify the value of the fields in the class,than the base class should have all of the fileds and accessor methods private.
Create a private constructor without parameters?
public class Base
{
private Base()
{
}
}
public class Derived : Base
{
//Cannot access private constructor here error
}
Make all the constructors of that class as private to stop inheriting, Though not recommended.
public class Immutable {
private int val;
public Immutable(int v)
{
this.val = v;
}
public int getVal() { return this.val; }
}
You can make your class immutable without using final keyword as:
Make instance variable as private.
Make constructor private.
Create a factory method which will return the instance of this class.
I am providing immutable class here in Java.
class Immutable {
private int i;
private Immutable(int i){
this.i = i;
}
public static Immutable createInstance(int i){
return new Immutable(i);
}
public int getI(){return i;}
}
class Main {
public static void main(string args[]){
Immutable obj = Immutable.createInstance(5);
}
}
Static classes can't be inherited from

How to access the private variables of a class in its subclass?

This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the question is: I need to access private members of class A from class B, rather than create variables with the same value in class B.
The interviewer was either testing your knowledge of access modifiers, or your approach to changing existing classes, or both.
I would have listed them (public, private, protected, package private) with an explanation of each. Then gone on to say that class A would need to be modified to allow access to those members from class B, either by adding setters and getters, or by changing the access modifiers of the members. Or class B could use reflection. Finally, talk about the pros and cons of each approach.
Reflection? Omitting imports, this should work:
public class A {
private int ii = 23;
}
public class B extends A {
private void readPrivateSuperClassField() throws Exception {
Class<?> clazz = getClass().getSuperclass();
Field field = clazz.getDeclaredField("ii");
field.setAccessible(true);
System.out.println(field.getInt(this));
}
public static void main(String[] args) throws Exception {
new B().readPrivateSuperClassField();
}
}
It'll not work if you do something like that before the of invocation readPrivateSuperClassField();:
System.setSecurityManager(new SecurityManager() {
#Override
public void checkMemberAccess(Class<?> clazz, int which) {
if (clazz.equals(A.class)) {
throw new SecurityException();
} else {
super.checkMemberAccess(clazz, which);
}
}
});
And there are other conditions under which the Reflection approach won't work. See the API docs for SecurityManager and AccessibleObject for more info. Thanks to CPerkins for pointing that out.
I hope they were just testing your knowledge, not looking for a real application of this stuff ;-) Although I think an ugly hack like this above can be legit in certain edge cases.
The architecture is broken. Private members are private because you do not want them accessed outside the class and friends.
You can use friend hacks, accessors, promote the member, or #define private public (heh). But these are all short term solutions - you will probably have to revisit the broken architecture at some stage.
By using public accessors (getters & setters) of A's privates members ...
You cannot access private members from the parent class. You have make it protected or have protected/public method that has access to them.
EDIT : It is true you can use reflection. But that is not usual and not good idea to break encapsulation.
A nested class can access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.
public class SuperClass
{
private int a = 10;
public void makeInner()
{
SubClass in = new SubClass();
in.inner();
}
class SubClass
{
public void inner()
{
System.out.println("Super a is " + a);
}
}
public static void main(String[] args)
{
SuperClass.SubClass s = new SuperClass().new SubClass();
s.inner();
}
}
If I'm understanding the question correctly, you could change private to protected. Protected variables are accessible to subclasses but behave like private variables otherwise.
By using setters and getters u can access it
From JLS §8.3. Field Declarations:
A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.
I write the example code:
public class Outer
{
class InnerA
{
private String text;
}
class InnerB extends InnerA
{
public void setText(String text)
{
InnerA innerA = this;
innerA.text = text;
}
public String getText()
{
return ((InnerA) this).text;
}
}
public static void main(String[] args)
{
final InnerB innerB = new Outer().new InnerB();
innerB.setText("hello world");
System.out.println(innerB.getText());
}
}
The explanation of the accessibility of InnerA.text is here JLS §6.6.1. Determining Accessibility:
Otherwise, 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.
You can use the setters and getters of class A. Which gives same feeling as if You are using a class A's object.
Have you thought about making them protected ? Just to be sure you are aware of this option, if you are then pardon me for bringing up this trivia ;)
Private members cant be accessed in derived class
If you want to access means you can use getter and setter methods.
class A
{
private int a;
void setA(int a)
{
this.a=a;
}
int getA()
{
return a;
}
}
Class B extends A
{
public static void main(String[] arg)
{
B obj= new B();
obj.setA(10);
System.out.println("The value of A is:"+obj.getA());
}
}
Private will be hidden until you have been given the right access to it. For instance Getters or setters by the programmer who wrote the Parent. If they are not visible by that either then accept the fact that they are just private and not accessible to you. Why exactly you want to do that??
I don't know about Java, but in some languages nested types can do this:
class A {
private string someField;
class B : A {
void Foo() {
someField = "abc";
}
}
}
Otherwise, use an accessor method or a protected field (although they are often abused).
A private member is accessible in subclass in a way that you cannot change the variable, but you are able to access the variable as read only.
Obviously, making them protected, or adding setters/getters is the preferred technique. Reflection is a desperation option.
Just to show off to the interviewer, IF "access" means read access, and IF Class A generates XML or JSON etc., you could serialize A and parse the interesting fields.
Class A
{
private int i;
int getValue()
{
return i;
}
}
class B extends A
{
void getvalue2()
{
A a1= new A();
sop(a1.getValue());
}
}
To access private variables of parent class in subclass you can use protected or add getters and setters to private variables in parent class..
You can't access directly any private variables of a class from outside directly.
You can access private member's using getter and setter.
Ways to access the superclass private members in subclass :
If you want package access just change the private fields to protected. It allows access to same package subclass.
If you have private fields then just provide some Accessor Methods(getters) and you can access them in your subclass.
You can also use inner class e.g
public class PrivateInnerClassAccess {
private int value=20;
class InnerClass {
public void accessPrivateFields() {
System.out.println("Value of private field : " + value);
}
}
public static void main(String arr[])
{
PrivateInnerClassAccess access = new PrivateInnerClassAccess();
PrivateInnerClassAccess.InnerClass innerClass = access.new InnerClass();
innerClass.accessPrivateFields();
}
}
4 .You can also use Reflection e.g
public class A {
private int value;
public A(int value)
{
this.value = value;
}
}
public class B {
public void accessPrivateA()throws Exception
{
A a = new A(10);
Field privateFields = A.class.getDeclaredField("value");
privateFields.setAccessible(true);
Integer value = (Integer)privateFields.get(a);
System.out.println("Value of private field is :"+value);
}
public static void main(String arr[]) throws Exception
{
B b = new B();
b.accessPrivateA();
}
}
You can use Accessors (getter and setter method) in your Code.
By using setter method you can use else with the help of refection you can use private member of class by setting that member say a -
take a from class
and set a.setAccessible(true);
You may want to change it to protected.
Kindly refer this
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If this is something you have to do at any cost just for the heck of doing it you can use reflection. It will give you list of all the variables defined in the class- be it public, private or protected. This surely has its overhead but yes, it is something which will let you use private variables. With this, you can use it in any of the class. It does not have to be only a subclass
Please refer to the example below. This may have some compilation issues but you can get the basic idea and it works
private void getPropertiesFromPrivateClass(){
Field[] privateVariablesArray = PrivateClassName.getClass().getDeclaredFields();
Set<String> propertySet = new HashSet<String>();
Object propertyValue;
if(privateVariablesArray.length >0){
for(Field propertyVariable :privateVariablesArray){
try {
if (propertyVariable.getType() == String.class){
propertyVariable.setAccessible(true);
propertyValue = propertyVariable.get(envtHelper);
System.out.println("propertyValue");
}
} catch (IllegalArgumentException illegalArgumentException) {
illegalArgumentException.printStackTrace();
} catch (IllegalAccessException illegalAccessException) {
illegalAccessException.printStackTrace();
}
}
Hope this be of some help.
Happy Learning :)
Below is the example for accessing the private members of superclass in the object of subclass.
I am using constructors to do the same.
Below is the superclass Fruit
public class Fruit {
private String type;
public Fruit() {
}
public Fruit(String type) {
super();
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Below is subclass Guava which is inheriting from Fruit
public class Guava extends Fruit{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Guava(String name,String type) {
super(type);
this.name=name;
}
}
Below is the main function where we are creating an object of subclass and also displaying the member of superclass.
public class Main {
public static void main(String[] args) {
Guava G1=new Guava("kanpuria", "red");
System.out.println(G1.getName()+" "+G1.getType());
}
}
Note that a private field of a superclass might be accessible to a subclass (for example,if both classes are memebers of the same class),Nevertheless,a private field is never inherited
by a subclass
Simple!!!
public class A{
private String a;
private String b;
//getter and setter are here
}
public class B extends A{
public B(String a, String b){ //constructor
super(a,b)//from here you got access with private variable of class A
}
}
thanks
Directly we can't access it. but Using Setter and Getter we can access,
Code is :
class AccessPrivate1 {
private int a=10; //private integer
private int b=15;
int getValueofA()
{
return this.a;
}
int getValueofB()
{
return this.b;
}
}
public class AccessPrivate{
public static void main(String args[])
{
AccessPrivate1 obj=new AccessPrivate1();
System.out.println(obj.getValueofA()); //getting the value of private integer of class AccessPrivate1
System.out.println(obj.getValueofB()); //getting the value of private integer of class AccessPrivate1
}
}
Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
Java Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement.
There is more information here:
http://tutorialcorejava.blogspot.in/p/java-modifier-types.html

Categories

Resources