【问题标题】:unable to instantiate class within method?无法在方法中实例化类?
【发布时间】:2014-03-24 15:18:41
【问题描述】:

我正在尝试从以下类实例化一个对象:

public class Name {

    //The unmodified name
    private String name;

    //The modified name
    private String preprocessedName;

    /**
     * Constructor method which stores the original name in the name variable
     * @param inputName
     */
    public Name(String inputName){
        //Store the name
        this.name = inputName;

        //Initialise the preProcessedName
        this.preprocessedName = null;   
    }

    /**
     * Retrieves the original name
     * @return the original name
     */
    public String getName(){
        return this.name;
    }

    /**
     * Stores the preprocessed name in the preprocessedName variable
     * @param the preprocessed name
     */
    public void setPreprocessedName(String processedInput){
        this.preprocessedName = processedInput;
    }

    /**
     * Retrieves the preprocessed name
     * @return the preprocessed name
     */
    public String getpreprocessedName(){
        return this.preprocessedName;
    }
}

在以下方法中:

/**
     * Private method which instantiates names as a name object. 
     * @param names
     */
    private void processInput(ArrayList<String> names){
        library = new ArrayList<Name>();
        for(String name : names){
            Name tempName = new Name("r");

            //Not bringing up any methods from the class
            **strong text**tempName.**strong text**



            //add to the library
            library.add(tempName);
        }
    }

当我创建对象时,我无法使用 Name 类中的任何方法,你知道为什么会这样吗?例如当我尝试自动完成时,它不会从类中调出 getter 和 setter。

【问题讨论】:

  • 忘记你的 IDE 是否提供了 getter 和 setter。当您只编写代码并尝试编译时会发生什么?
  • 一切看起来都不错,所以请尝试像 Kevin 建议的那样自己编写。只需更改:Name tempName = new Name("r"); 到 Name tempName = new Name(name); 我想你想这样做
  • 代码无法编译,似乎根本无法识别类内部的getter和setter,很困惑
  • 您是否导入了正确的 Name 类?
  • "add cast to tempName" ,但这并不能解决问题!

标签: java methods instantiation


【解决方案1】:

检查您在包中的导入。 您是否导入了正确的 Name 类?

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多