How to Access non static variable from Another Class without Creating New Object

时间:2018-06-05 05:05:53

标签: java class variables static static-methods

I want to be able to access a non static variables and non static methods from another class without creating a new object.

In the existing code of our project, its creating class instantiation issue due to new object creation.

See thew below creation both classes and their variables are non static.

Note : We have kept the variables and methods non static to support parallel tests execution using Test NG suite. Means same code must support multiple execution at a time. Hence can't alter the declaration to static as static variables can't support to execute in parallel.

Class 1 public class DataBaseQueries {

// non static Class variable
public int g_intDBNumericValue;

    // non-static method 
public Integer ecDBGetNumericValue(String Query){ 

Code logic to get numeric value from Data base.......
// returing extracted numeric value
return g_intDBNumericValue;
}

}

//Class 2 //Here inherited class Configuration is another Class say Class3 which is required and we don't have to extend Class 1 i.e., DataBaseQueries

public class CommonActions extends Configuration{

// non static Class variable
public int g_intSavedValueValue;

// non-static method to verify saved value public Integer ecSavedvalue{ g_intSavedValueValue=ecDBGetNumericValue("Select value from tableA where ID =100") }

}

public class Configuration{

// non static Class variables
public int g_int1....;

// non-static methods

public Integer ecSample{ g_intSavedValueValue=ecDBGetNumericValue("Select value from tableA where ID =100") }

1 个答案:

答案 0 :(得分:0)

尝试扩展课程,这是示例

public class SuperClass {
    public int getNb() {
         //specify what must happen
        return 1;
     }

     public int getNb2() {
         //specify what must happen
        return 2;
     }
 }

 public class SubClass extends SuperClass {
      //you can override the implementation
      @Override
      public int getNb2() {
        return 3;
     }
 }

Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2