The private modifier specifies that the member can only be accessed in its own class. But am I able to access it using a public method that get inherited from base class. Can someone explain me why? Does this mean object of Child class contain a member called b?
Here's the code:
package a;
public class Base {
private int b;
public int getB() {
return b;
}
public void exposeB() {
System.out.println(getB());
}
public Base(int b) {
this.b = b;
}
}
package b;
public class Child extends Base {
Child(int b) {
super(b);
}
public static void main(String args[]) {
Child b = new Child(2);
// Prints 2
System.out.println("Accessing private base variable" + b.getB());
}
}
you are not accessing the private variable in your super class directly. you are implementing the concept of Encapsulation. you are using the public getter method(in this case getB()) to make your private data accesed by other classes. thus, you can access private variable b through public getter but you never cant access b directly on its instace from another/subclass
In class Base, the field b is private but getB() is public so anybody can call that method.
What you can expect to fail compilation is something like:
System.out.println( "Accessing private base variable" + b.b );
(unless that line is called from within a method of Base itself).
You will not be able to access b directly in Child because it is private. You can, however, use the base-class's getB method which is public (and hence can be called anywhere).
To allow only extending classes and other classes in your package to access the field, you can declare it as protected.
class A {
private int n;
public A(int n) { this.n = n; }
public int n() { return n; }
}
class B extends A {
public B(int n) { super(n); }
public void print() { System.out.println(n); } // oops! n is private
}
class A {
protected int n;
public A(int n) { this.n = n; }
public int n() { return n; }
}
class B extends A {
public B(int n) { super(n); }
public void print() { System.out.println(n); } // ok
}
The private modifier means that you can't reference that field outside the class. Because getB() is public, however, you can reference that method. The getB() method can reference the private b field, because it's inside the class, and therefore can access it.
Private variable means that you can't access directly the variable from its class.... Declaring that variable private means that you can't do this
Myclass.myprivatevariable = 3
This will throw a compile error complaining that myprivatevariable is not visible fro the outside
But, as you did.... Declaring an internal method as getter or setter, public, you are allowing the user, only just through that method, to access indirectly that variable... That is always the preferred way to do.
Related
I have a jar for school that is supposed to be decompiled, modifed, and reevaluated. I decompiled all of the class files using the ECD plugin for Eclipse, but I think I have a few anonymous classes that were extracted and need to be merged back into another class. I have a class P, and then five more classes named P$1, P$2, ..., P$5.
Here's the problem parts of P:
public class P {
private ArrayList<Family> group;
private int marker;
private Integer primaryElement;
Comparator<Family> c;
public P(ArrayList<Family> g, Integer i, Comparator<Family> c) {
this.marker = -1;
this.group = new ArrayList(g);
this.primaryElement = i;
this.c = c;
}
/* Some unrelated methods */
public String printHeader() {
return this.print(new 1(this));
}
public String printRow(Integer i) {
return this.print(new 2(this, i));
}
public String printPad() {
return this.print(new 3(this));
}
public Object printCost() {
return this.print(new 4(this));
}
public String printLine() {
return this.print(new 5(this));
}
Here is P$1. The others are very similar.
final class P$1 implements PrintCommand {
P$1(P arg0) {
this.this$0 = arg0;
}
public String print(Family f) {
return String.format("%3d", new Object[]{Integer.valueOf(f.getId())});
}
}
In case you're wondering, PrintCommand is a super simple interface:
public interface PrintCommand {
String print(Family arg0);
}
How can I get P$1 merged back into P? Also, what does this.this$0 mean in P$1?
In an anonymous class you can reference the this from the enclosing class with P.this. To do that, the java compiler will create a constructor, which will set a field named this$0 to the reference passed to the constructor.
The original code probably looked like this:
public String printHeader() {
return this.print(new PrintCommand() {
public String print(Family f) {
return String.format(%3d", f.getId());
}
);
}
There are other things the compiler does, for example adding accessor methods for private methods/fields from the enclosing class that are accessed in the inner class. Or passing the value of (effectively) final variables used in the inner class to the constructor.
From the perspective of the Java Runtime, there is no anonymous inner class, only named classes.
When one object of a class has a reference to another object of
the same class, the first object can access all the second object’s
data and methods (including those that are private).
I took this sentence from a book. But I couldn't figure out actually what it means.
It means that private members are visible to other instances of the same class. For example:
class A {
private int v;
public boolean isSameV(A other) {
return this.v == other.v; // can acccess other.v
}
}
It means that if you have a class that looks like this
public class A {
private int number;
private A otherInstance;
public int number2;
public void DoStuff() {
...
}
}
you can access A.number in the DoStuff method (or any other class method) even although number is actually private.
e.g.
public class A {
...
public void DoStuff() {
this.otherInstance.number = 42;
^^^^^^^
cannot access private members here
}
}
is perfectly fine, while
public class B {
private A aInstance;
public void DoStuffToo() {
this.aInstance.number = 42;
}
}
would not compile, because B cannot access A's private members.
Good question actually, I faced similar problem when I started learning Java, here is how it looks in practice:
public class A {
private String example;
protected int anotherOne;
public A(){
}
public A(A a){
this.example = a.example; // here we get access to private member of another object of same class
this.anotherOne = a.anotherOne; // it works for protected as well
}
// This works for methods not just constructor, lets consider we want to swap value of example:
public void swapExample(A a){
String temp = a.example;
a.example = this.example;
this.example = temp;
}
}
Private fields can be accessed from inside of the class, by this construction you can access all the field of an instance of Foo without getters and setters when you are in class Foo :
public class Foo {
private String name;
public int sumLetter(Foo b) {
return this.name.length() + b.name.length();
}
}
The doc : Declaring Member Variables :
private modifier — the field is accessible only within its own class.
I have 2 classes that are not the main classes, but I want class B to access the variable from class A. I am not sure how to do it.
public class A (
public int humanCakes;
//This method is called by somewhere, when it is called it adds one
public void humanCakes() {
huamnCakes ++;
}
)
public class B {
public void addUp() {
Cakes = humanCakes + 4;
}
}
Since your variable in class A is public you can do the following
public class B{
int Cakes;
public void addUp(A obj)
{
Cakes = obj.humanCakes + 4;
}
}
Note that you must past the A object into the addUp method in order to get the reference to the humanCakes variable
I am trying o access a protected field of Inner class through
inheritance in another inner class. But i came across a problem:
package a;
class A{
public class Inner{
protected int i =5;
}
}
package b;
class B{
public class BInner extends A.Inner{
dsds
void test(){
System.out.println(i); // that's works fine, i
}
}
void print(){
System.out.println(new BInner().i) // but why i cant access this field from here? Compiler just says that there is protected access ...
}
}
Is there is way how to access this field?
The protected access modifier means that the field or method is available only to the class itself and its children. Since class B does not extend B.BInner, it cannot access B.BInner.i.
The most common way to work with access modifiers is to use getter/setter pairs, which you can declare in A.Inner (because that's where i is declared and B.BInner will inherit the methods):
class A{
public class Inner{
protected int i =5;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
}
Calling getI() on a B.BInner object will then return the value of i, and since it's public, it can be used anywhere.
As I understand the inherited class should also inherit variables, so why doesn't this code work?
public class a {
private int num;
public static void main(String[] args) {
b d = new b();
}
}
class b extends a {
public b() {
num = 5;
System.out.println(num);
}
}
num variable's access modifier is private and private members are not accessible out of own class so make it protected it will accessible from subclass.
public class a {
protected int num;
...
}
Reference of Controlling Access to Members of a Class
As i understand the inherited class should inherit also variables,
you got it wrong, instance variables are not overriden in sub-class. inheritence and polymorphism doesnt apply for instance fields. they are only visible in your sub-class if they are marked protected or public. currently you have super class variable marked private. no other class can access it. mark it either protected or public in-order for other class's to access it.
public class A{
public int num=5;
public static void main(String[] args) {
b d = new b();
d.c();
}
}
class b extends A
{
public void c()
{
System.out.println(num);
}
}
definitely this is what you need i think
private scope can only be accessed by the containing class.
For this to work num would need to be declared protected scope.
However this would also make it accessible to other classes in the same package. My recommedation would be to create a get / set method in order to maintain proper encapsulation.
you could then access num in class b by calling getNum()
Because you are using the private access modifier. If you use private to a instance variable or to a method it only can access inside the class only(even several classes include one source file). We can expose private variable to outside by using getters and setters. Following code will compile without an error
public class A {
private int num;
public void setNum(int num)
{
this.num = num;
}
public int getNum()
{
return num;
}
public static void main(String[] args)
{
B d = new B();
}
}
class B extends A
{
public B()
{
SetNum(5);
System.out.println(getNum());
}
}
You don't have access to private members of the base classes from the subclass. Only the members with modifiers of private/protected