How to use getters and setters in two different classes - java

how to use getter setter in two different class
Class A{
int a = 10;
GetterAndSetter gs = new GetterAndSetter();
gs.setValue(a);
}
Class GetterAndSetter {
int a ;
public void setValue(int a){
this.a = a;
}
public int getValue(){
return a;
}
}
class B {
int c;
GetterAndSetter gs = new GetterAndSetter();
c = gs.getValue();
}
While printing c it gives null. And tell me if it is valid or not.

Whenever you write this
GetterAndSetter gs = new GetterAndSetter();
what you're doing is to create a new instance of GetterAndSetter. Two instances that you create won't have any connection between them.
Inside class A, you create a new instance, and set its value. Inside class C, you create a new instance, and read its value. But because you've got two different instances, the value you're reading isn't connected with the value you're setting.
This is roughly like:
I buy an envelope, and put some money inside it.
Later on, I want to get the money back, so I buy a new envelope, and look for the money inside it.
You have to be looking in the same envelope that you put the money in, if you want to find it!

In class A, your code creates a new instance of GetterAndSetter and sets a value to the property. In class B, however, your code creates again another new instance of GetterAndSetter , then gets the value.
The instances your code works with in classes A and B are not the same - hence you don't obtain the values set in A when trying to get it in B. The instance of GetterAndSetter created in B is not used anymore after the code in B exits.
To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B. You can do this e.g. by passing it as a parameter to a method of B, or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter.
An example of the first option (pass as parameter):
Class A{
...
GetterAndSetter createAndSet();
int a = 10;
GetterAndSetter gs = new GetterAndSetter();
gs.setValue(a);
return gs;
}
...
}
class B {
...
void getValueFromGetterAndSetter(GetterAndSetter gs) {
int c;
c = gs.getValue();
...
}
...
}
To connect the instances, we of course also need to have another piece of code (assuming instances of A and B exist already):
...
b.getValueFromGetterAndSetter(a.createAndSet());
...

You have used different reference. You should use same reference so that only you can access the value.

you need to understand the basics of oops, you have created one instance inside class A and you are trying to access in Class B which is possible only if you pass the reference of that object from Class A to B. In that case you have to have the instance of GetterAndSetter which you have created in Class A in Class B, instead you have created another new instance which will create new reference in memory, and the class variable a will be null.

In your code, both class A and B create new objects for GetterAndSetter. Hence they are not shared between these classes. Thats why you are getting null.
I wounder how your code print null for C. I think it would be "0" instead.

It is valid, here is what happens:
You create object gs in class A
Then you set the value of a of that object to 10
You then create another object gs in class B
Last but not least, you ask the object gs from class B what its value for a is.
Guess what, its NULL as you did not set its value anywhere so it wont return one.

Related

Casting in Java - what does (Parent) this mean?

class A {
public int a = 100;
}
class B extends A {
public int a = 80;
}
class C extends B {
public int a = 10;
public void show() {
int a = 0;
System.out.println(a);
System.out.println(super.a);
System.out.println(((A) this).a);
}
}
What does ((A) this).a in the line System.out.println(((A) this).a); do?
Is it upcasting/downcasting thisor is something else happening here?
I also tried System.out.println(this); and System.out.println((A)this); and they both have the same output. What exactly is happening here?
In the java programming language, we have classes. When we write java code, we create instances of those classes, for example:
Object o = new Object();
Object is a class. Writing new Object() creates an instance of that class. The above code declares a variable o and assigns it [a reference to] an instance of class Object.
In the terminology of the java programming language, we say that variable o has type Object.
In the code in your question, a variable that is assigned an instance of class C, really has three types.
It has type C.
It has type B since B is the superclass of C.
It has type A because it indirectly extends class A also.
In the context of the code in your question, this is a special variable whose type is C. Writing (A) this is telling java to relate to the variable this as if its type is A.
Class A cannot access its subclasses. Hence it is only aware of its class member a. Hence when you write this line of code...
((A) this).a
You are accessing the member of class A only.
System.out.println(a);a is the one from the show method of your C class → a = 0
System.out.println(super.a);a is the one from the super-class of C, which is B → a = 80
System.out.println(((A) this).a);First, you cast your C instance (this) into A, then you call a which is a member of the A class → a = 100
There is also something to consider : method will always take the more specialized one (except if super is used), where field will be taken directly from the type referenced (even if there is an extending class).
For example, if I add getA() in each classes :
class A {
public int a = 100;
public int getA(){
return a;
}
}
class B extends A {
public int a = 80;
public int getA(){
return a;
}
}
class C extends B {
public int a = 10;
public int getA(){
return a;
}
public void show() {
int a = 0;
System.out.println(a);
System.out.println(super.a);
System.out.println(((A) this).a);
System.out.println(getA());
System.out.println(super.getA());
System.out.println(((A) this).getA());
}
}
class Scratch {
public static void main(String[] args) {
new C().show();
}
}
I get the following output :
0
80
100
10
80
10
Which means that in the case of the method, except in the case of super.getA() which explicitly goes to the superclass, casting your C into a A doesn't change much for methods, as it impacts the field.
If you write something like obj.a, obj.getA() or someMethod(obj), Java somehow has to find the actual field or method to be used, based on the type or class of obj. There are two distinct dispatch mechanisms involved (plus the special construct super).
Dynamic dispatch (polymorphism, overriding): This is used when calling an instance method on the object, as in obj.getA(). Then the runtime class of the obj is examined, and if this class contains a getA() method, this is used. Otherwise, the direct parent class is examined for a getA() method, and so on up to the Object class.
Static dispatch: In cases like obj.a or someMethod(obj), the runtime class of obj doesn't matter. Involved is only the compiler, and from his knowledge of obj's type, he decides which field or method to use.
super dispatch: If you write super.getA() or super.a, your getA() method or a field is ignored, and instead the next-higher class in the hierarchy is used that contains such a method or field.
In your case you have 3 fields plus one local variable, all with the same name a. (By the way, it's a very bad idea to have such name conflicts in professional code.) We are inside a method show() declared in the C class. Let's have a look at some different expressions and what they mean here:
a references the local variable a. There's no dispatch needed, it's just that local definitions take precedence over fields.
this.a is a static-dispatch expression, so it's important what the compiler thinks about the type of this. And that's always the class where this code has been written. In your case, it's class C, so the field a from class C is used, the one being 10.
super.a is a super-dispatch expression, meaning that the a field from this class C is ignored and the next higher one taken (the one from B, in our case).
((A) this).a is static dispatch, but the (A) casting has a significant effect. The expression before the dot originally comes from this, being of type C, but the (A) cast tells the compiler to believe it were of type A. This is okay, as every C also is an A, by inheritance. But now, static dispatch sees something of type A in front of the dot, and dispatches to the a field from the A class, and no longer from C.
getA(), this.getA() and ((A) this).getA() are all dynamic-dispatch examples, all giving the same result. The method called will be the one based on the runtime class of this object. This will typically be one defined in the C class. But if show() was called on an object of a subclass of C, e.g. D, and D had its own getA() method, that one would be used.
super.getA() is a case of super-dispatch, it will call the getA() method next higher up in the class hierarchy from the current class, e.g. B.
System.out.println(this);
And
System.out.println((A)this)
These two prints the object reference to class C with toString() method.
System.out.println(((A)this).a);
This is upcasting, child object to parent object.

Java Type System: Why do these assignments, method calls and type casts fail?

Let's say I have the following interface and classes defined:
public interface I { void a(); }
public class A implements I {
public void a() { System.out.println("A"); }
}
public class B implements I {
public void a() { System.out.println("B"); }
public void b() { System.out.println("C"); }
}
And then I run the following code:
public class Main {
public static void main(String[] args) {
A a = new A();
B b = new B();
I i;
i = a;
i.a(); // prints "A"
i = b;
i.a(); // prints "B"
i.b(); // 1st problem: i can't seem to find method b. Why?
b = i; // 2nd problem: b can't be assigned to i although i references an object of class B?
b = (B)i; // why does this work fine...
a = (A)i; // 3rd problem: ...but this here doesn't?
}
}
So here are my questions:
First Problem
Why can't i.b() be called?
i points to the same object as b, an object of class B which does have a method b.
So why does i.a() call the right method (the one that prints out "B") but i.b() doesn't resolve at all?
Does the fact that i was declared as being of type I (an interface) have anything to do with that? Does this mean that in an assignment X x = new Y() where Y extends X, one can only ever call methods on x that are already declared in X, and not just specific to Y?
Second Problem
Why can't b be assigned to i although i references an object of class B? b and i already reference the same object, don't they? So why does it cause an error if I try to assign b to i - the end result of which should be identical to the state of the program before that assignment, unless I'm missing something significant.
Third Problem
Why can I cast i to type B now although I couldn't assign b to i earlier, and why doesn't casting i to A work?
I'm assuming my confusion is somehow rooted in an unclear distinction between the reference variables and the objects they're referencing, as well as the differences between the types of these variables and objects. I just can't quite explain these occurrences - and in particular the first problem confuses me a lot.
For the first problem:
You can use the interface reference to call only the methods it declares
For the second problem:
You can use interface reference to invoke methods in the classes that implement the interface. However, there is no use to assign interface reference to a class reference since interface reference doesn't have any methods that can be invoked.
for the third problem:
You have assigned previously
i=b
and hence
b=(B)i
works fine.
However,
a=(A)i
wouldn't work because i stores b and not a
First of all, learn Java (and/or OO (object oriented)) programming...
Variable i is a reference to an object instance that implements interface I. Method b() was not declared in interface I, thus it is not visible through i.b().
To be able to call it, i needs to be casted, EG: ((B) i).b()
Variable b is a reference to an object that is an instance of class B, and cannot be assigned to any reference that itself is not declared as an instance of B.
Again, a cast needed, EG: b = (B) i
Class B is not a child of class A. They both implement interface I, but A is not parent of B.
It's not a problem at all but It's behavior of inheritance and polymorphism.
Please note that when you
I i = new A();
Left hand side (I) will tells compiler which all methods it can call using that reference.
Right hand side (A) will tells the runtime which method should execute using that method call
So in your case
1 Problem
you can not call b() since b() is not there in inteface I
2 Problem
you are casting interface to object b and then calling b() so its working fine.

Calling Constructor Multiple times

How to call the Constructor multiple times using the same object
class a
{
a(int i)
{
System.out.println(i);
}
public static void main(String args[])
{
a b = new a();
int x = 10;
while( x > 0)
{
//Needed to pass the x value to constructor muliple times
}
}
}
I needed to pass the parameter to that constructor.
Constructor of a class A constructs the objects of class A.
Construction of an object happens only once, and after that you can modify the state of the object using methods (functions).
Also notice if programmer does not write any constructor in his class then the Java compiler puts the constructor for the class (public constructor without any parameters) on its own.
In the case where a constructor has been provided by the programmer, the compiler does not create a default constructor. It assumes, the programmer knows and wants creation of the objects of his/her class as per the signature of the explicit constructor.
Constructor calls are chained. Suppose there exists below class relationship.
Child.java extends Parent.java and Parent.java extends GrandParent.java.
Now if Child child = new Child(); is done, only one object is created and that is of Child.java, but the object also has all of the features of GrandParent first then with the features of the Parent and then the Child.
Hence first constructor of GrandParent.java is called then Parent.java is called and lastly the constructor of Child.java is called.
Constructors are special and different from other methods.
The intent of constructors is to create the object, so each time you use the new operator, the constructor is called and a new object is created. You can not call the constructor directly. You need the new operator to call it. Even if you see some class defining methods like getInstance(), it still uses the new operator to construct the object and return the created object.
*PS there are ways to create an object without calling constructor (like Serialization) but that is out of context of the discussion here.
Constructors are called only once at the time of the creation of the object.
Can you please be specific about what you want to achieve?
But I think you could try one of the following two things.
Calling the constructor to create a new object and assigning it to the object 'b':
b = new a(1);
Using the setter method:
void setI(int i){
this.i = i;
}
b.setI(1);
int x = 10;
while( x > 0)
{
a b = new a(x);
}

How to set a field with out creating an object in java

I can't modify either Class A or Class B. And both Class A & B are huge in size (with several nested Classes and hundreds of parameters). And with multiple threads, memory foot print is impacting the performance.I'm checking all ways to reduce memory usage. Basically I'm trying to limit the scope of Class B instance so that GC can work on it at the earliest.
(For Your Information: I already knew that I can do by B b = new B(); b.setS("Calm Down"); a.setB(b);)
Here is the scenario:
Class A{
private B b;
public getB{return b}
public void setB (B b){this.b = b;}
}
Class B{
private String s;
//getters and setters for s}
Class MyNeed{
A a = new A();
// Here I'm trying to create an obj B and set S and then pass that obj to a.setB().
a.setB (new B().setS("Param S Set"));
}
So I guess that new B() is local to setB(). so in the very next line new B() is out of scope.
But this way in eclipse, I'm getting error that setB() can't accept void. I guess it is setS() returning void.
May be I'm missing some concepts. But I want to have something such simple. How to implement this.
You can try to have a constructor within the class A:
class A{
private B b;
public B getB(){
return b;
}
public void setB (B b){
this.b = b;}
}
public A(S s){
this.S = s;
}
}
So when you do a.setB(), you can just do a.setB(s) and that will set the object S for that A object.
a.setB (new B().setS("Param S Set"));
Ok, That statement starts by creating a new B instance, then it calls the setS method on that instance, passing it the string "Param S Set". Finally, it calls a.setB(...) passing the value returned by the setS() call.
As you already know, that doesn't work because setS() returns void.
May be I'm missing some concepts. But I want to have something such simple. How to implement this.
{
B b = new B();
b.setS("Param S Set");
a.setB(b);
}
What you are trying is wrong. setS() does not return B instance.
You will not save any resources by writing one-liners.
GC will also not clean anything if you set B to A as long as A has a reference to B.
I got it using builder design pattern. Thanks to #Builder by lombok.
Thank you all.

Sending arrays from actionPerformed() to another class

I have a calculation in an actionPerformed() method in class A. The results are two arrays containing doubles C[] and D[]. How can I send it to another class B?
There any number of ways you could achieve this.
The important parts are:
Have a reference to B
Have some kind of means for B to receive the values you want to send. I'd recommend a setter method of some kind
You could also use a common model, which is essentially the same, but exposes less about B to A making it more difficult for A to do naughty things to B it probably shouldn't ;)
Create an instance of class B and pass the result of the calculation to that instance.
This is a very basic problem and is easy to solve once you've had some experience. You might find the wiki on Object-oriented programming useful. Its powerful stuff once you understand it.
Here's some examples for you...
public class ClassB{
double multiplier;
public ClassB(){
//this will be called when you create an instance of class B
//with no arguments. Also called the default constructor, or empty-arg
//constructor.
multiplier = 2;
}
public void setMultiplier(double value){
multiplier = value;
}
public void calculate(double[] c, double[] d){
//do nifty stuff, like multiply every value in c and d!
for(int i=0;i<c.length;i++){
c[i] *= multiplier;
d[i] *= multiplier;
}
}
}
// and in your class having the action performed method...
//create an instance of class b. This will call the empty-arg constructor.
ClassB classB1 = new ClassB();
ClassB classB2 = new ClassB();
public void actionPerformed(ActionEvent e){
double[] c1 = new double[10];
double[] d1 = new double[10];
double[] c2 = new double[10];
double[] d2 = new double[10];
//call classB1 calculate method. This will multiply c1 and d1 by 2,
//as classb1's multiplier is 2.
classB1.calculate(c1, d1);
classB2.setMultiplier(4);
//call classB2 calculate method. This will multiply c2 and d2 by 4,
//as classb2's multipler has been set to 4.
classB2.calculate(c2, d2);
}
This is just a simple example of what object oriented programming can do for you. There's a ton more to learn than this, but as you're obviously just beginning I won't overwhelm you.
Try making both arrays C & D static. Making these static will allow other classes access to it. Otherwise, you should pass it through a parameter to the constructor.
Parameter Method:
public class A implements ActionListener{
Array C;
Array D;
Bclass B = new Bclass(C, D);
public void actionPerformed(){
//Do stuff to Arrays
}
}
public class Bclass{
Bclass(Array C, Array D){
//This is Constructor...
}
}
Static Method:
public class A implements ActionListener{
public static Array C;
public static Array D;
public void actionPerformed(){
//Do stuff to Arrays
}
}
public class Bclass{
Bclass(){
//This is Constructor...
A.C().getIndexOf("C-stuff");
A.D().getIndexOf("D-stuff");
}
}
You have tons of ways. The correct one for you depends on the structure of object model you use.
However, there are two basic concept you have to understand:
1. What is the "intersection point".
In order for A's instance (call it a1) to be able to communicate with B's instance (b1), a1 must have a way to "put his hands" on a reference to b1. A few example ways to do it are:
Each A get's a reference to B's instance as an argument to it's constructor, or another 'set' method, and then stores it as a field made for that purpose.
a1 and b1 share a common instance of class C. c can be the 'parent' of both a1 and b1 (i.e. contain both of them), or some 'manager' component that manage a certain process in your program.
The static \ singleton way. B class stores a static instance of itself, which allows reference to it from everywhere in the program.
2. What is the the desired communication interface
The interface one class exposes to others should be well designed in order to achieve many important concepts, e.g.: readability of code, security and 'hiding', reliability etc. This also depends on if both A and B are stored in the same package or are internal classes of each other or are even inherited from each other.
A few standard ways to communicate are:
Direct writing access: a field in B is publicly exposed and allows direct writing into it. this is mostly a bad behavior (a rule of thumb is that all fields should be at least protected if not private).
set methods: B has a set method that receives the calculated data, process it and stores it in it's fields (or pass it on).
Listening - A stores the calculated data in itself, and lets all of it's registered "listeners" know that a new data is available by calling an appropriate method in them. The listeners have read access to the relevant fields, or the data is passed as an argument, and then the listener (b1) decides what to do with the data.

Categories