This question already has answers here:
Accessing private instance variables of parent from child class?
(11 answers)
Closed 4 years ago.
can we modify a private variable through child class. We can use it by set and get methods but how can we modify them in child class.
You don't have a direct access to private members of parent class through child class. You can specify getters and setters with protected or public access modifier in parent class and change or read value of that private member of parent class by calling proper method - getter or setter.
Example of how you can achieve that:
class Parent {
private int member;
public void setMember(int member) { // setter
this.member = member;
}
public int getMember() { // getter
return member;
}
}
class Child extends Parent {}
public class TestClass {
public static void main(String[] args) throws IOException {
Child child = new Child();
System.out.println("member = " + child.getMember());
child.setMember(5);
System.out.println("member = " + child.getMember());
}
}
Output that you get:
member = 0
member = 5
No, you cannot modify private variables in a super class, unless you are using reflection.
The only way to access them would be getter and setter.
There is no way to change private from the other class.
You can change in the same class
class Parent {
private value;
public class Method {
System.out.println(value++);
}
}
Related
Today a fellow learner came up with an interesting query. We know that this keyword is used to refer to the current object. But I could not explain to him how this keyword behaves as seen in the following snippet. I know what inheritance is: allows access to parent class variables and methods. But are they copied into the memory area of child instance?, because I am able to use this keyword to access the parent class property.
I was able to refer to parent class variable. I searched and found that nothing gets copied virtually to child class, but why the following behavior happens? Please explain this case of using this.
class Parent {
int a=10;
}
public class Child extends Parent{
void m1(){
System.out.println(a);
System.out.println(this.a);
System.out.println(super.a);
}
public static void main(String[] args){
new Child().m1();
}
}
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The property a is inherited by Child. Therefore, you can use this.a in child to reference it.
Where was the problem supposed to be?
I searched and found that nothing gets copied virtually to child class
You have the wrong example to illustrate that statement.
The way to understand that is (roughly): "instance variables are not overridden when re-declared in subclasses, so you can't declare an instance as Parent and expect to get Child.a if the instance was created with new Child()". Here's an example of the problematic case:
class Parent {
int a = 10;
}
public class Child extends Parent{
int a = 12; //not overridden
public static void main(String[] args){
Parent child = new Child();
System.out.println(child.a); //This will print 10, not 12
}
}
System.out.println(child.a); will print 10 because variables instance fields don't get overridden. You get the value based on the declared type (Parent in this case)
When you instantiate a class Child it contains all members of itself and of Parent. However, private members of Parent are not accessible from Child:
class Parent {
private int p = 10;
}
public class Child extends Parent{
void m1(){
System.out.println(p); // compilation error
}
}
Another interesting case is when one instance of Parent tries to access a private field of another instance of Parent. What do you think happens?
public class Parent {
private int p = 11;
public boolean same(Parent other) {
return other.p == p;
}
}
You might think other.p will result in a compilation error since p is a private field. However, since privacy does not pertain to object instances, but to classes. So all private fields in Parent are visible within all Parent instances, so this works!
Consider below Code:
this is a reference variable which will point to the current object.
super is used to refer to Parent's property in case you have created
the same in the child.
class Product{
String color;
public Product() {
color = "Black";
}
}
class Mobile extends Product{
String color;
Mobile(){
color = "White";
}
void showMobileData(){
System.out.println("this hashCode is "+this.hashCode());
System.out.println("super hashCode is: "+super.hashCode());
System.out.println("color is: "+color);
System.out.println("this.color is: "+this.color);
System.out.println("super.color is: "+super.color);
}
}
public class Test {
public static void main(String[] args) {
//new Mobile().showMobileData();
Mobile mRef = new Mobile();
System.out.println("mRef HashCode: "+mRef.hashCode());
mRef.showMobileData();
}
}
This question already has answers here:
How to create objects from a class with private constructor?
(6 answers)
Closed 7 years ago.
I want to create object of Base class in another class but Base class constructor is defined as private
Here is my Code
public class Main
{
public static void main(String ... args)
{
//Base objBase = new Base();
//objBase.show();
}
}
class Base
{
private Base()
{
}
public void show()
{
System.out.println("Base Class Show() Method");
}
}
Code inside Base is still allowed to call the constructor, which means it's possible to create objects in a static method:
class Base
{
private Base()
{
}
public void show()
{
System.out.println("Base Class Show() Method");
}
public static Base createBase() {
return new Base();
}
}
and then call the method to create an object:
Base objBase = Base.createBase();
objBase.show();
You cannot create objects of classes if they have private constructors. Objects can be constructed, but only internally. That is how it is.
There are some common cases where a private constructor can be useful:
Singletons
Classes containing only static methods
Classes containing only constants
Type safe enumerations
Hoping this helps.
when you extend a private class. Are the public and protected members of class become private. if not any explanation.
if you extend a nested private class, it wont change public/protected modifiers of the members. Here is an example :
public class Clazz {
private static class NestedClazz {
public int value = 123;
}
public static class NestedClazzExt extends NestedClazz {
}
}
you can now access the inherited member: value from outside
public static void main(String[] args) {
NestedClazzExt nestedClazz = new Clazz.NestedClazzExt();
System.out.println(nestedClazz.value);
}
you can create private class in side a class . We call it as Nested classe. Means a class inside a class. The Concept itself is saying that you can create private class in side another class. The private class will act like as data member to the outer class.
So, You can't extend the private class.
Based on your query I tried to prepare a simple class.
public class pvtClass {
private class As {
public String abc = "private attribute";
public void print(){
System.out.println("privateClass");
}
}
class Ab extends As{
public String ab = "extended attribute";
public void printAb(){
System.out.println("extended class");
print();
System.out.println(abc);
}
}
public static void main(String as[]){
Ab ab1 = (new pvtClass()).new Ab();
As as1 = (new pvtClass()).new As();
ab1.printAb();
as1.print();
System.out.println(as1.abc);
}
}
If you have a look at this class, I have a private class named "As" which has public attribute and public methods. I have another class named "Ab" which extends "As". I have written a main method to invoke the private attribute and methods.
below is the output for the code snippet:
extended class
privateClass
private attribute
privateClass
private attribute
There is a difference between the access of the members of a class and the access to the type itself.
public class C {
private class InnerP1 {
public void m() {
System.out.println("InnerP1.m()");
}
}
private class InnerP2 extends InnerP1 {
public void p() {
this.m();
System.out.println("InnerP2.p()");
}
}
public InnerP1 strange() {
return new InnerP2();
}
}
In this example, the interface I is visible from outside class C. The classes InnerP1 and InnerP2 are not visible from outside C. Jave itself makes not restrictions to the visibility of types you use in your public interface. The method strange() of class C returns a result of class InnerP1. Since outside of C we do not know anything about the class InnerP1 other than it is subtype of Object, the only thing we can do is use the result of strange() as an Object.
public class D {
public static void main(String[] args) {
C c = new C();
Object o = c.strange();
if(o.equals(c.strange())) {
System.out.println("Strange things are going on here!");
}
}
}
As #KnusperPudding pointed out already, the visiblity of public members is not changed, we might just not have enough knowledge of the type itself to access them.
Access to members cannot be restricted by sub-classing. When you mark a class as private then access via the class name is restricted i.e. to the same .java file, however once you have an instance of this class it can be accessed at least as easily as the super class.
This question already has answers here:
Why can outer Java classes access inner class private members?
(10 answers)
Closed 9 years ago.
public class Test {
public static enum MyEnum {
valueA(1),valueb(2),valuec(3),valued(4);
private int i;
private Object o;
private MyEnum(int number) {
i = number;
}
public void set(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
public static void main(String[] args) {
System.out.println(MyEnum.valueA.i); // private
}
}
output: 1
Why 1 is shown if it a private member in enum?
Outer classes have full access to the member variables of their inner classes, therefore
i is visible in the Test class.
In contrast, if MyEnum was external to the Test class, the compiler would complain about the visibility of i,
It's (i) a member field being referenced within the same class (MyEnum); no access modifier prevents that - the private access modifier defined on i will prevent it's visibility outside this class.
Suggested Reading
private access from a containing type to a nested type is permitted, see Why are private fields on an enum type visible to the containing class?
vlaueA is considered a static variable so you can call it within MyEnum since i in the
same enum whice play the same as a class so MyEnum can access valueA which can access i
Outer class will have the access to inner class member even if it is private because you have defined main method inside the outer class.
What is the example of indirect access to private member of superclass from subclass?
A nested class has 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.
Quote from http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
In the quote, we talk about "nested" class
here is an example of how an inner class can access private fields of the outer class.
class OuterClass {
private int x = 7;
public void makeInner(){
InnerClass in = new InnerClass();
in.seeOuter();
}
class InnerClass {
public void seeOuter() {
System.out.println("Outer x is " + x);
}
}
public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass().new InnerClass();
inner.seeOuter();
}
}
Finally, if you extend a class with the InnerClass, they will also access the private fields of the OuterClass if your InnerClass is public or protected
It is to be supposed (but the compiler does not enforce it, only warns), that a private method will end being used by a public, protected or default method (otherwise it is useless).
So, the extending class can "indirectly" call the private method by calling the public, protected or default method that ends calling the private method.
Yes, we can access private members of a superclass in the child class through the public method of the superclass which can be invoked from the child class's reference variable heaving the reference id of child class.
for example:-
class Base
{
private int x=10;
void show()
{
System.out.println(x);
}
}
class Child extends Base
{
public static void main(String... s)// public static void main(String[] args)
{
//rom jdk 1.7 main can be defined like above
Child c=new Child();
c.show();
}
}
The output will be 10