Set and get a static variable from two different classes in Java - java

Lets say I have 3 Classes: A, Data, and B
I pass a variable from class A which sets that passed variable to a private variable in class Data.
Then in class B, I want to call that specific variable which has been changed.
So I do
Data data = new Data();
data.getVariable();
It will then return null, since in class Data I initialize variables to nothing (ex: int v;), and I think that class B is initializing a brand new class and resetting the values to default, but I don't know how to fix this.
I know that the variable is setting properly because in class A if I do data.getVariable() it will print the variable that was set.
Class A:
Data data = new Data();
int d = 1;
data.setVariable(d);
Class Data:
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
Class B:
Data data = new Data();
private int v;
v = data.getVariable();
System.out.println(v);
This will print out 0 instead of the actual value

When you instantiate a Data object in class A, and instantiate another Data object in class B, they are two different instances of the Data class. They both instantiate d to 0 by default. You then call setVariable on the instance in class A and pass it the value of 1; but the instance in class B remains in 0. In order to change the value of the instance in class B, you would need to call setVariable on the instance in class B.
What it seems like you're looking for is a static member. Static members are the same across all instances of the same class. Just put the static keyword before the method(s) or field(s) that you want to use it. Static members and fields are typically accessed using the name of the class in which they are declared (i.e. MyClass.doMethod()). For example:
Class Data (updated):
private static int b;
public static void setVariable(int s)
{
b = s;
}
public static int getVariable()
{
return b;
}
Class A:
Data.setVariable(d);
Class B:
v = Data.getVariable();
System.out.println(v);

Editing - my first suggestion was to use static for variable b, and the author changed his question adding that suggestion.
It fixes what you are trying to do. I write the example in code that compiles:
public class Demo {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.doWhatever();
b.doSomethingElse();
}
}
class Data {
private static int b;
public void setVariable(int s)
{
b = s;
}
public int getVariable()
{
return b;
}
}
class A {
public void doWhatever() {
Data data = new Data();
int d = 1;
data.setVariable(d);
}
}
class B {
Data data = new Data();
private int v;
public void doSomethingElse() {
v = data.getVariable();
System.out.println(v);
}
}

Related

How to get value of getter in class C which was setted in Class A (which was declared in Class B)

I am having three classes Class A which set Value, class B where both getter and setters are created, Class B which get value (set in Class A)
Because I was creating new instances of Class B in Class A and Class C. I am not able to get value in class Cwhioch was set in Class A.
What I acknowlegeds is We need to pass the reference to Class C instance from class A to Class B.
But I dont know how to do so.
I tried with this code. I know the result it is not possible. I dont know how to do it.
public Class A {
int X = 9;
B b = new B();
b.setValue(X);
}
public Class B {
private float value = 0;
public float getValue() {
return value;
}
public void setValue(float value){
this.value = value;
}
}
public Class C {
B b = new B();
final float x = b.getValue();
}
I expect when I use getValue() method of class B in Class C. I am able to get the value putted in Class A by setValue() method
Whenever you create an object using the "new" keyword, remember that you are creating a new object and a new memory space is alloted to it.
Now in class C, when you create a new object of B, a new memory space is alloted to this instance b.
(This instance b does not point to the same memory location that b in class A points to)
Immediately after the object is created, you are calling b.getValue() which will only give you the default value of "value".
when I use getValue() method of class B in Class C. I am able to get
the value putted in Class A by setValue() method
In order to get the value set in A, you need to call getValue() of b --
the object b which is in class A
(and not the object b which is declared in class C)
So you need to access it using a.b.getValue() in class C.
you may do that by adding public static property inside a Class.
Static property are associated to the class directly. they can be called even without creating an instance of the class, ex: ClassName.propertyName.
public Class B {
public static float value = 0;
}
inside Class A you can set B float value like this :
public Class A {
B.value = 9;
}
and get the value :
public Class C {
final float x = B.value;
}
First of all the instance of class B in Class A and Class C are different.
You don't have any getter in A class to get the Class B field values
You can create a method in Class C and pass by reference of instance in Class A.
Hope this helps you..
You may do that in the following way:
public class A {
int X;
B b;
public A(int x, b b){
this.b = b;
this.b.setValue(X);
}
}
public class C {
B b;
public C(B b){
this.b = b;
}
public float getX(){
return b.getValue();
}
}
Now you pass the same reference of B class to both class A and C as shown below:
public static void main(String[] args){
B b = new B();
A a = new A(9,b);
C c = new C(b);
float x= c.getX();
}
Finally, I am able to solve my question thanks for your suggestions.
But I actually did it. I made my getter and setter static. Now I don't need to create reference again to get value.
My code
public Class A {
int X = 9;
B b = new B();
b.setValue(X);
}
public Class B {
private static float value = 0;
public static float getValue() {
return value;
}
public void setValue(float value){
B.value = value;
}
}
public Class C {
final float x = B.getValue();
}
Try this out!!
In the Constructor of ClassA, pass reference of ClassB and set the Value.
public class ClassA {
int X=9;
ClassB b;
public ClassA(ClassB b){
this.b = b;
this.b.setValue(X);
}}
Similarly, In constructor of ClassC, pass reference of ClassB and call the method getValue() to retrieve the value set by classA.
public class ClassC {
ClassB b;
public ClassC(ClassB b){
this.b = b;
}
public float getX(){
return b.getValue();
}}
Class B has the setter and getter function. In the main function, create an instance for ClassB and pass the same reference to ClassA and ClassC.
public class ClassB {
private float value = 0;
public float getValue() {
return value;
}
public void setValue(float value){
this.value = value;
}
public static void main(String[] args){
ClassB b = new ClassB();
ClassA a = new ClassA(b);
ClassC c = new ClassC(b);
float x= c.getX();
System.out.println(x);
}}

Creating an array of subclasses of a class

I'm trying to store all subclasses of A which are constructed by super() in the array child (in this case B). All the children are in the same package. This is my approach but I don't know how the class could store itself inside an array or pass itself as argument to super().
class A {
static int i = 0;
A[] child = new A[10]
int someval;
A(int val){
someval = val;
child[i] = ???;
i++;
}
}
class B extends A{
B(){
super(val);
}
}
Is this even Possible? With my approach B will only be added when a new B() is created? Is it possible to get a complete array without creating a new object?
public class A {
private static final List<A> instances = new ArrayList<>();
public A() {
instances.add(this);
}
public static List<A> getInstances() {
return instances;
}
}
Now A.getInstances() can be called whenever you like, and will contain instances of anything that extends A.

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 instantiate an object in java?

I'm new in programming and I would like to know where did I go wrong in instantiating an object. Below is the code:
public class Testing{
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
Sample myTest = new Sample();
System.out.println(c);
}
}
There is no Sample class in your code . The one which you have declared is a private method .
// private method which takes an int as parameter and returns another int
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
With the current snippet , You need to instantiate the Testing class and make use of the Sample method. Notice your class definition is preceded by the keyword class , in this case class Testing.
public class Testing{
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
Testing t = new Testing(); // instantiate a Testing class object
int result = t.Sample(1); // use the instance t to invoke a method on it
System.out.println(result);
}
}
But that doesn't really make sense, your Sample method always returns 3 .
Are you trying to do something like this :
class Sample {
int a;
int b;
Sample(int a, int b) {
this.a = a;
this.b = b;
}
public int sum() {
return a + b;
}
}
public class Testing {
public static void main(String[] args) {
Sample myTest = new Sample(1, 2);
int sum = myTest.sum();
System.out.println(sum);
}
}
I doubt you actually want to create an object.
From your code snippet, I understand that you want to run a 'method' named Sample which adds two numbers. And in JAVA you don't have to instantiate methods. Objects are instances of class. A method is just a behavior which this class has.
For your requirement, you don't need to explicitly instantiate anything as when you run the compiled code JAVA automatically creates an instance of your class and looks for main() method in it to execute.
Probably you want to just do following:
public class Testing{
private int sample(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int c = sample(1, 2);
System.out.println(c);
}
}
Note: I changed Sample to sample as it's generally accepted practice to start a method name with lower-case and class name with an upper-case letter, so Testing is correct on that front.
You instantiating correctly with new keyword ,But your calss name and method invoking is wrong
Testing myTest = new Testing();
int result =myTest.Sample(1); //pass any integer value
System.out.println(result );
Sample is not a class, it is just a method. You cannot create instances of it.
You only run it -
int sample = Sample(3);
If you wish for sample to be a class, define it as a class.
In your case, the method is not static is so you cannot directly access it from the Static method Main. Make it static so you could access it. Or just create a new instance of Testing and use it -
Testing testing = new Testing();
int sample = testing.Sample(3);
Sample method returns integer, so get the result and use it anywhere.
public static void main(String []args)
{
int myTest = Sample(4555);//input may be any int else
System.out.println(myTest);
}
This is how you should be doing this.
public class Testing{
public int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
// Creating an Instance of Testing Class
Testing myTest = new Testing();
int c =0;
// Invoking the Sample() function of the Testing Class
System.out.println(myTest.Sample(c));
}
Well , it's easy. To you instantiate an object in Java you should to use class name and to do with that it class received a valor. For exemplo :
...Car c1 = new Car();

Getting value of private not primitive field using reflection

Presume we have two different packages... one package can't be accessed but we like to know the value of a complex field called b.
public class A {
private String whatever;
private B b;
private static class B {
final ArrayList<Z> c = new ArrayList<Z>();
private void addItem(Z z) {
this.c.add(z);
}
private Z getItem(int nr) {
return this.c.get(nr);
}
}
}
public class Reflect extends A {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
Reflect ref = new Reflect();
Class getA = ref.getClass().getSuperclass();
Field getB = getDeclaredField("b");
getB.setAccessible(true);
Class bInst = getB.getClass();
Method bMeth = bInst.getMethod("getItem", Integer.TYPE);
Object zInst = bMeth.invoke(new Integer(123));
}
}
How can I get the value if I don't get the complex type B from the package ?
Still get java.lang.NoSuchMethodException: stackOver.A.getItem(int) even I set the field gstB accessible ....
The only thing you are missing is that getField only gives you public accessible fields.
Field getB = getA.getDeclaredField("b");
will give you any field of that class.
A longer example
class Main {
public static class A {
private String whatever;
private B b = new B();
private static class B {
final ArrayList<String> c = new ArrayList<String>();
private void addItem(String z) {
this.c.add(z);
}
private String getItem(int nr) {
return this.c.get(nr);
}
}
}
public static class Reflect extends A {
public static void main(String... ignored) throws Exception {
Reflect ref = new Reflect();
Class getA = ref.getClass().getSuperclass();
Field getB = getA.getDeclaredField("b");
getB.setAccessible(true);
Object b = getB.get(ref);
Method addItem = b.getClass().getDeclaredMethod("addItem", String.class);
addItem.setAccessible(true);
addItem.invoke(b, "Hello");
Method getItem = b.getClass().getDeclaredMethod("getItem", int.class);
getItem.setAccessible(true);
String hi = (String) getItem.invoke(b, 0);
System.out.println(hi);
}
}
}
prints
Hello
How can I get the value if I don't get the complex type B from the package ?
You can get it as an Object, and then use reflection to further discover the methods that it exposes.
Object bInst = ... // Get b through reflection
Class bClass = bInst.getClass();
Method[] bMeth = bClass.getMethod("getItem", Integer.TYPE);
Object zInst = bMeth.invoke(new Integer(123));
Use commons beanutils library and use following method, it is much cleaner than doing it yourself
PropertyUtils.getNestedProperty(ref, "b.propertyOfClassB");
replace propertyOfClassB with actual property name.

Categories