首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java访问包

用Java访问包
EN

Stack Overflow用户
提问于 2016-01-17 07:23:44
回答 2查看 66关注 0票数 0

我在ReadSource类中设置了字符串消息,我希望从access方法的驱动程序类中访问它,但是它显示的是null,而不是消息。我尝试在汽车setName( String )中打印消息,它显示正确的字符串,但是我无法在我的主类中访问它。

我的问题可以通过测试下面的代码来说明。

有人能帮我或者解释一下吗?非常感谢。

代码语言:javascript
复制
package Driver;

import Util.ReadSource;
import Model.Automotive;
public class Driver {
    public static void main(String args[]){

        Automotive auto = new Automotive();
        ReadSource read =  new ReadSource();

        String main = "Message";
        //set the message and display
        read.set(main);

        //get the message that was set in the read.set(String)
        auto.getMessage();
    }

}
package Util;

import Model.Automotive;
public class ReadSource {


    public void set(String message){
        Automotive auto = new Automotive();
        System.out.println("This messasge is in getMessage in the
  class ReadSource "+ message);
        //Set the name for automotive
        auto.setName(message);
    }
}
//This the the ouput
/*This messasge is in getMessage in the class ReadSource Message
Message is Message
This messasge is in getMessage in the class Automotive null*/
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-17 08:08:39

代码语言:javascript
复制
public class Driver {
public static void main(String args[]){

    Automotive auto = new Automotive();
    ReadSource read =  new ReadSource(auto);

    String main = "Message";
    //set the message and display
    read.set(main);

    //get the message that was set in the read.set(String)
    auto.getMessage();

    System.out.println(auto.getMessage());
}

public class ReadSource {

Automotive auto;

public ReadSource(Automotive auto) {
    this.auto = auto;
}

public void set(String message) {

    System.out.println("This messasge is in getMessage in the  class ReadSource: " + message);
    //Set the name for automotive
    auto.setName(message);
}

}

代码语言:javascript
复制
public class Automotive {

String name;

public String getName() {
    return name;
}

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

public String getMessage() {
    return name;
}

}

票数 0
EN

Stack Overflow用户

发布于 2016-01-17 07:40:34

在ReadSource.set()方法中。您正在创建一个汽车的新实例。然后,在创建汽车的新实例(从此不再使用)之后,通过set方法再次传递消息的值。您想要做的是在类主体的开头创建一个变量(从技术上讲,定义上是一个字段)。

代码语言:javascript
复制
public class ReadSource {
     private String message;

     public void setMessage(String message) {
         this.message = message;
     }

     // make a getter to return it somewhere else
}

现在,可以在主类中使用auto.getMessage() (或类似的东西)访问消息。

那么,如果你主要是:

代码语言:javascript
复制
System.out.println(auto.getMessage());

它将打印传递给setMessage()方法的任何内容。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34836110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档