2017-07-02 10 views
-1

パスワードオブジェクトを初期化し、文字列の文字数をカウントするなどの目的で、同じオブジェクトを文字列として使用することに問題があります。私は、メソッドが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

。 –

+1

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

答えて

0

あなたの実際のgetText()方法は意味がありません。
機能的なデータを提供するように設計されていないので、実際には必要ありません(役に立たない計算)、それは不器用です。toString()

あなたの目標に到達するには、非常に基本的です。

ストアPasswordインスタンスのフィールドのテキスト:

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

そしてtextフィールド上のビューを提供します。

あなたは、このようにgetText()を置き換えることができます:

public String getText(){  
    return text; 
} 
は `のtoString()`メソッドをオーバーライドして、必要な値を返す
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' 
    } 
} 

thisPasswordインスタンスであるString.valueOf(this)の問題は、valueOf()方法は、からフィールド. 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`フィールドにPasswordインスタンスを変換する方法の絶対にないアイデアを持っていないということです上記の例。

あなたは間違いなくdocs about classesを読む必要があります。私はあなたが何か基本的なものを欠いていると思う


注:また、ためにセキュリティへの影響のため、文字列にパスワードを保存することはありませんが、それは全体他の物語だし、あなたの質問の範囲を超えて。あなたがPasswordインスタンスのtoString()方法からStringを再作成しようと

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

関連する問題