Trying to access data from one class in another. - java

Being new to Java but an old hand on older procedural languages and structured programming, I have a question on how to accomplish something in Java
I have three classes, let's say they're called CLASSA, CLASSB, and TESTCLASSA. CLASSA has a class definition with instance variables, and a constructor for some data. TESTCLASSA creates an instance of CLASSA and passes data to CLASSA by creating an instance of the object for CLASSA. SImiliarly CLASSB has another class definition with instance variables, and a constructor for some data. TESTCLASSA creates an instance of CLASSB and passes data to CLASSB by creating an instance of the object for CLASSB. I am trying to access CLASSB's data from CLASSA. Can someone suggest how I might go about doing this. Many thanks in advance for any assistance/suggestions you can provide.
Wayne Hann

Either declare the variable as public:
public class classA {
public Integer data;
}
or create a public getter (preferred), such as:
public class classA{
private Integer data;
public Integer getData() {
return data;
}
}

If you want to access properties of class B from class A then it's either possible that you create a object of B in the method from where you want to getData like
private String nameofA;
public String getNameofA() {
return nameofA;
}
public void setNameofA(String nameofA) {
this.nameofA = nameofA;
}
public String getClassBData(){
B b = new B();
return b.getNameofB();
}
else you create a class level instance or dependency of B type.
public class TestClassA{
public static void main(String[] args) {
B b = new B();
b.setNameofB("class B Name");
A a = new A("class A Name",b);
}
}
class A{
private String nameofA;
private B b = new B(); //either this
public String getNameofA() {
return nameofA;
}
public A(String nameofA, B b) {//or constructor
super();
this.nameofA = nameofA;
this.b = b;
}
public void setNameofA(String nameofA) {
this.nameofA = nameofA;
}
public String getClassBData(){
B b = new B(); // or creating local instance
//but here a new instance will be created
return b.getNameofB();
}
}
Then only you will be able to access the data of instance of B. Anyway you if your method in B is not private or protected(assuming A doesn't extend B), you can access the method by creating or passing a instance of B to the method of "A" from where you want to access.

Related

Class A instantiates a Class B instance. How can the Instance of ClassB call a method of class A?

I have 2 classes, and I have made one class (Class A) instantiate a Class B object.
I have a method in Class B that I want to call a method in Class A.
I'm working on a larger project for practicing Java, so I am simplifying things here.
// Class A:
public class ClassA {
private int number;
private ClassB instanceOfB = new ClassB();
public ClassA {
number = 0;
}
public void incrementNumber {
number++;
}
public void incrementNumberLongWay {
instanceOfB.incrementNumberInA()
}
}
// Class B:
public class ClassB {
public void incrementNumberInA() {
// My desire: Call Class A's incrementNumber method
// What should I put here?
}
}
How do I make sure incrementNumberLongWay works? Class A has been instantiated, and it's method incrementNumberLongWay is called, so this should call ClassB's method incrementNumberInA
I know this seems extremely convoluted, but the reason I'm doing this, is because in my program I'm not incrementing numbers, but instead doing some logic in Class B, and only wanting to affect Class A in certain cases.
You can't do this with the code provided. Relationships are by default one way. B doesn't know about A so cannot access it.
What you can do is pass a reference of A to B in it's construction process and then access A via that reference.
One solution would be to pass a method of A as a callback.
For example:
public class ClassA {
private int number;
private ClassB instanceOfB = new ClassB();
public ClassA {
number = 0;
}
public void incrementNumber {
number++;
}
public void incrementNumberLongWay {
instanceOfB.incrementNumberInA(this::increment);
// alternatively
// instanceOfB.incrementNumberInA(() -> incrementNumber());
}
}
public class ClassB {
public void incrementNumberInA(Runnable callbackMethod) {
callbackMethod.run();
}
}
This removes B's dependency on A, and instead allows a general callback mechanism.
However, for such a simple scenario this approach isn't advised.
It's probably a bad idea in general to have a circular dependency in this way. One approach to break the cycle would be to have a third class (classC?) that implements the increment logic (or whatever your real-world equivalent is), and have classA and classB instances each reference classC. That way there's no case where two classes know about each other.
ClassB doesn't know anything about ClassA. So, you couldn't do it.
The ugly decision is
public void incrementNumberLongWay() {
instanceOfB.incrementNumberInA(this);
}
and in
public class ClassB {
public void incrementNumberInA(ClassA cl) {
cl.incrementNumber();
}
}
You can't call methods from class A from class B as class B has no reference to an object of class a. You could, however, pass class A's current number state to class B as parameter, and return a value from class B which class A can then get and use.
For example:
public class A {
private int number;
public A(int number) {
this.number = number;
}
public void incrementNumber(boolean largeIncrement) {
if(largeIncrement) {
B bInstance = new this.B();
number = bInstance.incrementNumberLongWay(number);
}
else {
number++;
}
}
private class B {
private B() {
// if some initialization is needed...
}
public int incrementNumberLongWay(int num) {
num += 1000;
return num;
}
}
}
Hope this is what you wanted.

Transferring an object over multiple class instances

I am thinking of an optimum design pattern which I can use to transfer objects to the methods in different classes other than passing them as arguments.
class A{
}
class B{
public A a;
public B()
{
a = new A();
}
}
class C
{
public void c()
{
//need to access "a" of class B other than passing "a" as argument;
}
}
Here, a in class A attribute needs to be accessed in many other class methods. Is there an optimum design pattern or any possible way other than passing this object (a) as arguments?
It's hard to say how your program is really structured but two options come to mind:
Pass an instance of B to C's constructor.
class A {};
class B {
public A a;
public B() {
a = new A();
}
};
class C {
public B b;
public C( B b ) {
this.b = b;
}
public void someMethod() {
System.out.println( b.a );
}
};
If only one instance of class A ever exists (ie a Singleton). That means that class B holds an instance of class A, not each instance of class B holds an instance of class A.
class A {};
class B {
public static final A a = new A();
};
class C {
public void someMethod() {
System.out.println( B.a );
}
};

Java, how to get reference of an object

Let's say I have 3 classes; A , B and C. Class A and B are in one package. C is in another package. B is having a public function that returns a boolean value.
Object of B is created in Class A and he can call the functions of Class B. But the problem is that in Class C I want to have the reference of Class B object created by Class A, I don't want to create one more Class B object in Class C.How can I get that.
Example: Class B and Class A are in same package
B.java
class B
{
public boolean fun()
{
returns boolValue;
}
}
A.java
class A
{
B b = new B(); //Creates object of Class B and can access function.
}
Class C is in another package and different project also.
C.java
class C
{
//How to get the reference of Class B object created in Class A?
}
Once I get the reference to that I am going to call the functions of Class B to get the values. I tried writing some get() which returns the object of class B but to call that function I should have the object. But I don't know how to do that. This might be easy but I am new to java and I don't know how to do that. Please do help me to solve this problem.
**UPDATE : I can't create Class A object in Class C :( **
Make class A public
publi class A {
private static B b = new B(); //Creates object of Class B and can access function.
public static B getB() {
return b;
}
}
class C
{
//I want to get the reference of Class B object created in Class A....But How??? :(
B b = A.getB(); //if it works ????
}
Classes A and B need to be public and class A needs to provide a public accessor to the required field.
public class B {
}
public class A {
public B getB() {
return this.b;
}
}
Note that in your current code structure you will not be able to automatically instantiate B from your A object outside of a method.
You can create an A object in the class description but to initialize B you'll need to use the class constructor.
public class A {
private B b = new B();
public B getB() {
return b;
}
}
public class C {
private A a = new A();
private B b;
public C() {
b = a.getB();
}
}
or, if you don't want to create A, you may make it static.
public static class A {
private static B b = new B();
public static B getB() {
return b;
}
}
public class C {
private B b;
public C() {
b = A.getB();
}
}
You have to get access in C to A class and then share B reference by field.
So you may do something like this:
class B { //your function... }
class A {
B b = new B();
public B getB() { return b }
}
class C {
A a = new A();
public B getB () { return a.getB() }
}
}
Add a constructor to class C with object b as parameter
public class C{
private B bObj;
public C(B b){
bObj=b;
}
}
call this constructor from within your A class, which will create a reference to the created B object and you'll have this ref in bObj.

creating an object that shares its property among classes

I would like to make an object of a class A and it is initialized in class B, class C, and class D
This object should be shared; that is if any changes made to objA in these classes(C and D), its content remains the same even after objC,'objD' are destroyed, supposely that class B is the main class. I would like to use its property is class B
class A {}
class B
{
initialize class A object and use-change its property
initialize class C object and use-change its property
initialize class D object and use-change its property
}
class C{initialize class A object and use-change its property}
class D{initialize class A object and use-change its property}
class X{initialize B and destroy objC,objD, from objB use property of objA of class B}
A non static attempt would look like this:
Your target object:
public class A {
}
Your classes, that do something with the object:
public class C {
private final A a;
public C(final A a) {
this.a = a;
}
public foo() {
// do something with a
}
}
public class D {
private final A a;
public D(final A a) {
this.a = a;
}
public otherFoo() {
// do something with a
}
}
Your main class:
public class B {
public static void main(String[] args) {
final A a = new A();
final C c = new C(a);
final D d = new D(a);
c.foo();
d.otherFoo();
}
}
Try making the object static that way any changes made to one instance of that object will be consistent across all objects that use that object that are in the same thread.
This is essentially a singleton pattern, you can pass your class around or get it from the main. I prefer the latter personally, like so:
public class YourMain {
private final ClassA clazzA;
private final ClassB clazzB;
private final ClassC clazzC;
private final ClassD clazzD;
public YourMain() {
this.clazzA = new ClassA();
this.clazzB = new ClassB(this);
this.clazzC = new ClassC(this);
this.clazzD = new ClassD(this);
this.clazzB.doSomething();
}
public ClassA getClassA() {
return this.clazzA;
}
}
From there, you can chain back up to your main class in the other classes:
public class ClassB {
private final YourMain project;
public ClassB(YourMain project) {
this.project = project;
}
public void doSomething() {
this.project.getClassA().someMethod();
}
}
Of course, this isn't 100% what you would implement it like (you need to mind the order you load things in if you are passing your main class instance), but for something like this I usually find it is the cleanest and provides the easiest availability to all my classes across a project.

Java: invoking method

In Java, I have something like this
public class A {
private String title;
public A () {
// do something
}
public void run () {
B b = new B();
b.run();
}
public void changeTitle(String newTitle) {
this.title = newTitle;
}
}
public class B {
public B() {
// do something
}
public void run() {
}
}
My question is in method run() of B, is it possible to invoke method changeTitle() in A to change the title of the instance of A that instantiates B?
Thanks
B can only invoke methods on A if it contains a reference to an instance of A. You could pass an instance of A into B to achieve this.
public void run () {
B b = new B(this);
b.run();
}
public class B {
private A a;
public B(A a) {
this.a = a;
a.changeTitle("Ha!");
}
}
if B accepts a type A in its constructor, and when you say new B, pass in 'this' similar to
public void run () {
B b = new B(this);
b.run();
}
now you have a copy of the A object your working with.
Sure. Pass an instance of A in the constructor for B.
This will only be possible if you pass this as argument when you invoke B's run() method.
Not unless you arrange for instances of B to know what instance of A they should do that to (e.g., by passing that into the constructor for B and remembering it).
If you're doing something like this then you should consider, e.g., what you want to happen if an instance of B is created by something other than an instance of A.
no. As such an instance of B does not know who created it.
However with B as:
public class B {
private A creator;
public B(A creator) {
this.creator = creator;
// do something
...
}
and creating new B(this) in A.run(), B could call creator.changeTitle("whatever") in its run() method.
Is B is a non static inner class of A you van invoke the mehods of A (and access its fieldes).

Categories

Resources