如何将一个类的值用于另一个类从main方法调用

时间:2016-09-17 15:01:00

标签: java

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);       
    }  
}

如何从第一堂课的主要方法中使用第二级调用的第二个asd值。

**Third class**

1 个答案:

答案 0 :(得分:3)

根据@Maroun Maroun和@Bennyz的评论,你可以在你的两个类中创建一个getter和setter方法:

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;
    }
}

在编码时(不仅仅是阅读),了解这一点的好网站是CodeAcademy

要在第三节课中使用它,您可以这样做:

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!
    }

}

<小时/> 您的代码也有一些不正确的事情:

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();
    }
}

<小时/> 根据@ cricket_007的评论,public class()方法的更好解决方案是:

public class One {

    String asd;

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

这样,当制作One对象(One one = new One)时,它的asd字段已经为“2d6”。