Home > Blockchain >  How to get variable value of one method of a class into another class
How to get variable value of one method of a class into another class

Time:06-05

Please check the image, I have explained requirememnt

I want to get value of a in class xyz Image

CodePudding user response:

It is impossible to get a value from a variable inside a method if it does not return this value as a result of the method. If a variable is defined inside a method, it is created at the beginning of the method and destroyed at the end. If you want to use the class variable, then define it inside the class.

    class ABC {
    public static int a = 1;
    ...methods...
    }
    
    class XYZ {
    public static void main(String[] args) {
    System.out.println(ABC.a);
    }

Or this way:

class ABC {
  public static int getValue() {
  int a = 1;
  return a;
  }
}

class XYZ {
  public static void main(String[] args) {
  System.out.println(ABC.getValue());
}

CodePudding user response:

Can create an Interface that will implement by the child's class.

interface ABC {
    public static int a = 1;
}

class XYZ implements ABC {
    public static void main(String[] args) {
        System.out.println(a);
    }
}
  • Related