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.
Related
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 am have an interface with an inner class. Now the question is, why cannot I access the functions defined in the outer interface in a similar way to how methods are accessed in outer classes?
I thought things should just work smoothly as this inner class would only be instantiated after a class, implementing the outer interface, being instantiated.
Anyways the error I got was "No enclosing instance of the type OterInterface is accessible in scope"
public interface OterInterface {
public void someFunction1() ;
public void someFunction2() ;
public class Innerclass{
public String value1;
public String value2;
public String getValue1() {
OterInterface.this.someFunction1();
return value1;
}
}
}
Consider what instance of OterInterface you are attempting to perform 'someFunction' on. 'this' refers to the current object - OterInterface is an interface and as such does not have a current object.
So you can't reference OterInterface.this from there, as the compiler has no idea which object instance you are referring to!
In this case you can use anonymous inner class. As you can't instantiate any interface it is impossible to access their methods. Interfaces are incomplete classes with unimplemented methods. In order to instantiate it you have to provide the implementation for its methods.
public interface OterInterface {
public void someFunction1() ;
public void someFunction2() ;
public class Innerclass{
public String value1;
public String value2;
public String getValue1() {
new OterInterface(){
public void someFunction1() {
System.out.println("someFunction1()");
}
public void someFunction2() {
System.out.println("someFunction2()");
}
}.someFunction1();
return value1;
}
}
}
I have a base class and subclass. Base class has common methods and its implementation which I want to use in subclass but I want to use subclass member variable instead of superclass. I do not want to rewrite the same method in subclass. Is there a way in Java to achieve this.
You could create a protected setter on the member variable & then override the value of the super's variable within the constructor of the subclass:
class Animal {
private String voice = "Oooo";
protected void setVoice(String voice) {
this.voice = voice;
}
public void speak() {
System.out.println(this.voice);
}
}
class Dog extends Animal {
public Dog() {
setVoice("woof");
}
}
You can use a method to access the member and override it in subclasses.
Class A{
public void DoStuff(){
int aux = getResource;
/*cool things with aux*/
}
protected int getResource(){
return internal_member;
}
private int internal_member;
}
Class B extends A{
private int another_member;
#Override
public int getResource(){
return another_member;
}
}
But take into account that this will not prevent people chaging class A from using the member directly, It might be better to create a base class for the members and the getters.
Another Option, as some people outlined before is to have the data member in the base class as protected and initialize it in the subclass:
Class A{
public void DoStuff(){
/*cool things with internal_member*/
}
protected List internal_member;
A(){internal_member = /*Set here a value*/}
}
Class B extends A{
B(){internal_member = /*Set a different value here! you can even declare a member and assign it here*/}
}
You can use constructors with arguments if you need.
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
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.