Access object created in one class into another

前端 未结 2 1816
后悔当初
后悔当初 2021-01-19 03:52

I have a primary class as below:

public class classB{

  public classC getObject(String getstring){
     return new classC(getstring);
    }
}
2条回答
  •  生来不讨喜
    2021-01-19 04:39

    If you want to get the object created in classB a static field should do the job

    public class classB {
    
      public static objectCReference;
    
      public classC getObject(String getstring){
         objectCReference =  new classC(getstring);
         return objectCReference;
      }
    }
    

    Then you can access the reference in A

    public classA {
      int a = 0.5;
    
      if (classB.objectCReference != null) { // Make sure to null check 
        classB.objectCReference.methodC(a); 
      }
    
    }
    

    Also please follow the language conventions and start your class names with capital letters.

提交回复
热议问题