-8

I am completely new to Java... :(

I need to pass a variable from a parent class to a child class, but I don't know how to do that. The variable is located in a method in the parent class and I want to use it in one of the methods of the child class.

How is this done?

public class CSVData {
    private static final String FILE_PATH="D:\\eclipse\\250.csv";

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

    }
}

and then the other class

public class UserClassExperimental3 extends CSVData  {
    public static void userSignup() throws InterruptedException {
    //some code here   
    String firstname= firstname1; //and here it doesnt work
    }
}

Actually I think I succeeded doing that this way:

added the variable here:

    public static void userSignup(String firstname1)

then used it here:

    String firstname=firstname1;
    System.out.println(firstname);

But now I can't pass it to the method that needs it.

Kaloyan Kalinov
  • 87
  • 1
  • 2
  • 6
  • 2
    Can you show us what you've tried? Please give a code example. – Marco Corona Jul 10 '13 at 14:45
  • Unless you instantiate the child class from the parent's `method`, there is no way (other than reflection) to access a private method member of a parent class even tho you have a parent reference. Either make the child's variable public and/or static and access directly as `myChildInstance.myVar` or `MyChildClass.myVar`, or instantiate the child class and pass in the variable via a constructor, sort of like `new MyChildClass(myVar);` – Shark Jul 10 '13 at 14:46
  • Just examine this carefully http://stackoverflow.com/questions/3564663/parent-package-class-accessible-from-child-packge-class-in-java?rq=1 – hellzone Jul 10 '13 at 14:48
  • A Parent class should not have a dependency on a Child class. – Sotirios Delimanolis Jul 10 '13 at 14:51
  • 1
    edited my question, please have some mercy on me – Kaloyan Kalinov Jul 10 '13 at 14:53
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. 3) *"I really need to do this quickly.."* From my perspective, you need better time management skills. But even if you do need something 'quickly' best not to mention that to us. It makes you sound like you think we should answer your question first, over other (better prepared) questions asked by other people. (We disagree, in case all the close/down-votes were unclear.) – Andrew Thompson Jul 10 '13 at 14:58
  • Im sorry :( I will not do that anymore. – Kaloyan Kalinov Jul 10 '13 at 15:06

2 Answers2

2

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();
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • THANK YOU SO MUCH!!! 4 days I've been fighting with this and now it all works, thanks to you! – Kaloyan Kalinov Jul 10 '13 at 15:45
  • Do I do the same thing for the 4 more variables that I need to transfer? – Kaloyan Kalinov Jul 10 '13 at 15:46
  • You're welcome! You can pass the four more variables in the same way. Note that as the number of arguments grows larger, it becomes more difficult to ensure that all the callers pass them in the correct order. When this happens, an alternative is to pass the data instead via setters like setFirstName(). If you want the data to remain immutable during the lifetime of the class, use the **Builder pattern**, with the same setters but in a separate class. – Andy Thomas Jul 10 '13 at 16:18
  • can I pass the whole array and "deserialize "it there? – Kaloyan Kalinov Jul 11 '13 at 06:46
0
public class Main {

    public static void main(String[] args) {
        User user=new User();
        user.setId(1);
        user.setName("user");
        user.setEmail("user@email.com");

        user.save();
    }
}

public class User extends Model {

    private int id;
    private String name;
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

import java.lang.reflect.Field;

public class Model {

    public void save(){
        for(Field field: Model.this.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                System.out.println(field.getName()+"="+field.get(Model.this));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return;
    }
}
Armali
  • 18,255
  • 14
  • 57
  • 171