2

One.java

public class One {
    String asd;

    public class() {
        asd="2d6"
    }    

    public static void main(String args[]) {
        Two a = new Two();
    }
}

Two.java

public class Two {
    ArrayList<String>data;
    String asd;

    public Two(String asd){
        this.asd=asd;
        data.add(this.asd);       
    }  
}

How do I use this asd value of second for third class calling from first class's main method.

**Third class**
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183

1 Answers1

3

Per comments of @Maroun Maroun and @Bennyz, you can create a getter and setter method in your Two class:

import java.util.ArrayList;
public class Two {

    ArrayList<String> data;
    String asd;

    public Two(String asd) {
        this.asd = asd;
        data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
        data.add(this.asd);
    }

    // Get value of 'asd',
    public String getAsd() {
        return asd;
    }

    // Set value of 'asd' to the argument given.
    public void setAsd(String asd) {
        this.asd = asd;
    }
}

A great site to learn about this while coding (so not only reading), is CodeAcademy.

To use it in a third class, you can do this:

public class Third {
    public static void main(String[] args) {
        Two two = new Two("test");

        String asd = two.getAsd(); //This hold now "test".
        System.out.println("Value of asd: " + asd);

        two.setAsd("something else"); //Set asd to "something else".
        System.out.println(two.getAsd()); //Hey, it changed!
    }

}


There are also some things not right about your code:
public class One {
    String asd;

   /**
   * The name 'class' cannot be used for a method name, it is a reserved
   * keyword.
   * Also, this method is missing a return value.
   * Last, you forgot a ";" after asd="2d6". */
    public class() {
        asd="2d6"
    }    

    /** This is better. Best would be to create a setter method for this, or
    * initialize 'asd' in your constructor. */
    public void initializeAsd(){
        asd = "2d6";
    }

    public static void main(String args[]) {
        /**
         * You haven't made a constructor without arguments.
         * Either you make this in you Two class or use arguments in your call.
         */
        Two a = new Two();
    }
}


Per comment of @cricket_007, a better solution for the public class() method would be:
public class One {

    String asd;

    public One(){
        asd = "2d6";
    }
}

This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.

J. Kamans
  • 575
  • 5
  • 17