[Solved] Passing a variable from parent to child class in Java


The variable firstname1 is a local variable. You can’t access it outside its scope – the method.

What you can do is pass a copy of the reference to your subclass.

Since you’re calling a static method, the easiest way is to pass the reference as an argument to the method call:

@Test
public static void main() throws IOException {
 //some code here
  String firstname1 = array.get(2).get(1);
   UserClassExperimental3.userSignup( firstName1 );
}


public class UserClassExperimental3 extends CSVData  {
   public static void userSignup( String firstNameArg ) throws InterruptedException {
     //some code here   
     String firstname = firstnameArg; // Now it works
   } 
}

That said, since you’re using inheritance, you might find it useful to use an instance method. Remove “static” from the method. In main(), construct an instance of the class, provide it the name, and call the method on the instance.

@Test
public static void main() throws IOException {
 //some code here
   String firstname1 = array.get(2).get(1);
   UserClassExperimental3 instance = new UserClassExperimental3( firstName1 );
   instance.userSignup();
}

public class UserClassExperimental3 extends CSVData  {
   private String m_firstName;
   public UserClassExperimental3( String firstName ) {
      m_firstName = firstName;
   }
   public void userSignup() throws InterruptedException {
     //some code here   
     String firstname = m_firstname; // Now it works
   } 
}

If you also add userSignup() to the CSVData class, you can refer to the specific subclass only on creation. This makes it easier to switch the implementation, and it makes it easier to write code that works regardless of which subclass you’re using.

   String firstname1 = array.get(2).get(1);
   CSVData instance = new UserClassExperimental3( firstName1 );
   instance.userSignup();

4

solved Passing a variable from parent to child class in Java