How to access variable from owner instance? [duplicate] - java

This question already has answers here:
calling a function in a class's "owner" class
(8 answers)
Is there a way to access the variables of the calling class in a method?
(3 answers)
Closed 3 years ago.
An instance a of class A has an instance b of class B.
How can b access a variable of a?
class A {
boolean flag;
B b;
public static void main(String[] args) {
A a = new A();
}
public A() {
b = new B();
b.doSomething();
chageFlag();
b.doSomething();
}
void changeFlag() {
// do something with flag
}
// other stuff
}
class B {
void doSomething() {
// here I need to access a from the instance owning b.
boolean aFlag = ?? // how to access a.flag ??
}
}

You will not be able to access a variable of A in this instance because A and B have no parent/ child or outer/inner class relationship here.
The way to do this is to pass the instance of A to B, such as,
B b = new B(this);
For this you need to adjust the constructor to take in A as a parameter.

As your code is, b has no way of reaching a; simply because it does not have a reference to it.
If the two classes are so related that you need b to know about a, then you can make B an inner class in A:
class A {
boolean flag;
B b;
public static void main(String[] args) {
A a = new A();
}
public A() {
b = this.new B();
b.doSomething();
changeFlag();
b.doSomething();
}
void changeFlag() {
}
class B {
void doSomething() {
boolean aFlag = flag;
}
}
}
B.doSomething() is able to read flag from the enclosing class because B is an inner class.
Be aware that this solution is not appropriate in all situations, it makes the coupling between the two classes even tighter.

Related

When does the members of the class initialize? [duplicate]

This question already has answers here:
Java order of Initialization and Instantiation
(2 answers)
Closed 3 years ago.
Exactly when the Class members are initialized ?
In below code:
public class A{
public B b = new B();
private C c = new C(123);
public A (arg a){
// Do something
}
public someMethod(){
Log.i(TAG, " "+ b.getD());
}
}
main(){
A a = new A ("xyz"); }
When would be the Object of Class B & C created? And is it guaranteed to be created?
Should a professional app use such code or not ?
You can analyze the question this way:
class Scratch {
public static void main(String[] args) {
A a = new A ("xyz");
}
}
class A{
public B b = new B();
private C c = new C(123);
public A (String a){
System.out.println("new A()");
}
}
class B {
public B() {
System.out.println("new B()");
}
}
class C {
public C(int i) {
System.out.println("new C()");
}
}
which executes giving the following output:
new B()
new C()
new A()
which matches wiith the answer of #Jakir Hossain.
So: inline fields initializers are executed before code in constructor, following the same order which they are declared in.
Instances of classes B and C are created on A's instance creation, before A's constructor is executed. This ordering (and fields' initialization) are guaranteed.
When an object is created, the following things are done in the following order:
The object is allocated on the heap with the correct object type,
and all instance fields are "default initialized" to zero, false or
null.
The expressions in the super(...) or this(...) are evaluated and the
constructor for the next class up the chain is called. (This
recurses up the chain constructor, so that the Object constructor
gets executed first.)
The instance variable initializers and any instance initializer
blocks are executed in order.
The body of the constructor is executed.
The constructor returns.
Hope it helps you.

Java inheritance fields [duplicate]

This question already has answers here:
Is there a way to override class variables in Java?
(17 answers)
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 5 years ago.
I am not able to understand the following output.
I don't know why the output is 10, I think the line A a = new B() creates a new instance of class B, I think the result should be 20
class A {
int i = 10;
}
class B extends A {
int i = 20;
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.i);
}
}
Why this works like this .. please explain.
First, see Hiding Fields (emphasis added)
Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different
In other words, this isn't "inheritance" since you're actually hiding A's i behind B's i, and you are using a reference object of A, so you are getting its fields. If you did B b = new B(), you would see 20, as expected.
If you expect true overrides, try using methods.
class A {
public int get() {
return 10;
}
}
class B extends A {
#Override
public int get() {
return 20;
}
}
See
A a = new B();
System.out.print(a.get()); // 20
If you really want to see both at once, see this example.
class A {
int i = 10;
}
class B extends A {
int i = 20;
#Override
public String toString() {
return String.format("super: %d; this: %d", super.i, this.i);
}
}
And
A a = new B();
System.out.print(a); // super: 10; this: 20
In java you cannot override an instance variable. The output you are getting is expected. In Java you can only override instance methods and not instance variables.
If you want 20 as an output you may use getter methods over those instance variables.
class A {
int i = 10;
int getI() {
return i;
}
}
class B extends A {
int i = 20;
int getI() {
return i;
}
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.getI());
}
}
Polymorphism is not applicable for fields in Java.Evaluating Variables decision is taken at compile time so always base class variables are accessed.
Because you define 2 variables: one in the subclass B, and one with the same name in superclass A.
A a = new B();
a.i; // refers to A.i
If you cast the A to a B, it will access B.i:
System.out.println(((B)a).i);
I think you need to use 1 variable:
class A {
int i;
public A() {
i = 10;
}
}
class B extends A {
public B() {
i = 20;
}
}
public class MainClass {
public static void main(String[] args) {
A a = new B();
System.out.println(a.i); // will print 20
}
Member variable i is already defined in class A.
In order to achieve what you are looking for, change the class B as shown below:
class B extends A {
public B() {
i = 20;
}
}

how to access an instance of a class from its instance variable

So I have this scenario
class A:
public class A {
B b = new B();
public void doSomething() {
// this does something
}
}
and class B:
public class B {
public B() {
// need to access A
}
}
The problem is that I need to access the instance of A from the A's instance variable B. How do I do that?
You may simply pass the instance of A to B:
class A {
B b;
A() {
b = new B(this);//<-- A's instance
}
}
class B {
A a;
B(A a) {
this.a = a;
}
}
If class Bneeds to access an existing instance of A then you must provide the B instance with a reference to the A instance.
class B {
private A a;
B(A a) {
this.a = a;
// do something with a
}
}
then
A a = new A();
B b = new B(a);
If you need access to the A only within the constructor then you don't need to store a local copy of the reference.
You must create new object from instance A
A aa = new A();
OR
public class B extends A {
public B() {
// need to access A
}
}
Inner Class seems like the best thing to do ,
public class A {
B b = new B();
private int tryToAccess;
public void doSomething() {
// this does something
}
public class B{
public B()
{
tryToAccess=5;
}
}//B ends
}//A ends
Note:This is just one way of going about it , here you can access A's private variables from class B

how to reference an instance created in another class

I have a function in Class A which I would like to change the value of a field in Class B.
Class C has my main() and creates a new instance of class B and Class A. Class A is from an API and one of their functions is a listener function. I would like for that listener function to be able to change the field of Class B, but when I write the code for the listener function, it doesn't recognize Class B's instance.
How do I reference that instance?
Example code:
public class A {
public void listenermethod(){
//can't reference Binstance <-------
}
}
public class B {
B.field = 1;
}
public class C {
A Ainstance = new A();
B Binstance = new B();
}
You should give A class a private B field, and then you can call the public methods from B on this field as needed. If you need to create both A and B instances in a separate class (C) you should give your A class a public void setB(B b) setter method.
A.java
class A {
private B b;
public void setB(B b) {
this.b = b;
}
public void listenerMethod() {
if (b != null) {
b.someBMethod();
}
}
}
C.java
public class C {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.setB(b);
a.listenerMethod();
}
}
You have to be able to modify both class C and class A. Rewrite the class A method to
public void listenermethod(Binstance theB){
theB.something = "some_value";
}
Now when you call class A, pass in the Binstance. If you can't modify class A, then your task can't be done.
An instance by definition belongs to an object. Therefore, your class A must either have an object of class B as a member:
Class A{
private B instance_of_b;
}
now you can access B members like this:
instance_of_b.member
or the field belonging to class B could be static and then A could access it through the class.
B.member
Also make sure you know the meaning of accessor keywords (private,protected,[friendly],public).

I need an explanation of when to use class variables?

Suppose we have a class like:
public class test {
int a=1;
static int b=1;
public int getA()
{
return a;
}
public void incrementA()
{
a++;
}
public void incrementB()
{
b++;
}
public int getB()
{
return b;
}
}
and I have a class with main method like this
public class testmain {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
test t= new test();
t.incrementA();
test t1= new test();
test t2= new test();
t2.incrementB();
test t3 = new test();
test t4= new test();
t4.incrementB();
System.out.println("t= "+t.getA());
System.out.println("t1= "+t1.getA());
System.out.println("t4= "+t4.getB());
System.out.println("t3= "+t3.getB());
System.out.println("t2= "+t2.getB());
}
}
I need the explanation about why t and t1 have different value of a, and all t2, t3, t4 have the same value of b. I know that I have declared b as static and all objects access the same address of that variable b. Why it is not causing any problem for a variable when each object it has its own a, now my question is since all the objects look to the same location in memory then why is a different value of each object?
Every object has its own exemplar of a. So there are as many a's as objects
Class (static) variable value will be accessible multiple instances of the class, In this case t...t4.
When you change 'b' using t.b (or) t4.b (or) test.b (or) using any methods of t..t4--> same 'b' value will be updated, becuase only one copy of 'b' exists across these.
Instance variable is specific to that instance. 'a' exists a copy for each instance t...t4.
Read this link for more details.

Categories