2017-07-02 65 views
-1

我初始化了一个Password对象,并且在为计算字符串中的字母数量等后期目的而将同一对象用作字符串时遇到了问题。我知道我只能通过方法String.valueOf.toString获取对象的文本表示。我如何去取得我的对象传递,并获得我初始化它的“你好”字符串?将实例化对象转换为字符串

public class Password { 

public Password (String text) { 
} 

public String getText(){ 
    String string = String.valueOf(this); 
    return string; 
} 
public static void main (String[] args) { 
    Password pass = new Password ("hello"); 
    System.out.println(pass.toString()); 
} 

}

+0

覆盖了'的toString()'方法,并返回所需的值。 –

+1

https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html –

回答

0

您的实际getText()方法没有意义:

public String getText(){ 
    String string = String.valueOf(this); 
    return string; 
} 

您尝试重新从Password实例的toString()方法String
这真的没有必要(无用的计算),它很笨拙,因为toString()不是为了提供功能数据而设计的。

为了达到您的目标,这是非常基本的。

Store中Password实例的字段中的文本:

public Password (String text) { 
    this.text = text; 
} 

,并提供了text领域的看法。

你可以用这种方式取代getText()

public String getText(){  
    return text; 
} 
0

使用领域。

public class Password { 

    private String text; // This is a member (field) It belongs to each 
          // Password instance you create. 

    public Password(String value) { 
     this.text = value; // Copy the reference to the text to the field 
          // 'text' 
    } 
} 

String.valueOf(this)的问题,其中thisPassword实例,就是valueOf()方法完全没有了如何将Password实例转换为场的想法. You named it "Password", but it could also be MYTEXT or MySecret . So you need to tell how a密码instance can be displayed as text. In your case, you'll need to just use the从text`场上述例子。

你一定要阅读docs about classes。我认为你错过了一些基本的东西。


注意:您也永远不应该密码存储到一个字符串,因为安全隐患,但是这完全是另外一个故事,超越你的问题的范围。