ここでは、私が最初のtoString()メソッドを使用しようとしている、非常に基本的なクラスがあります。toStringメソッドを使用して調整済みの変数を出力する
public class Shoes
{
private String style;
private String color;
private double size;
public Shoes()
{
this.style = " ";
this.color = " ";
this.size = 0;
}
public Shoes(String newStyle, String newColor, double newSize)
{
this.style = newStyle;
this.color = newColor;
this.size = newSize;
System.out.println(this);
}
public String getStyle()
{
return style;
}
public void setStyle(String newStyle)
{
style = newStyle;
}
public String getColor()
{
return color;
}
public void setColor(String newColor)
{
color = newColor;
}
public double getSize()
{
return size;
}
public void setSize(double newSize)
{
size = newSize;
}
public String toString()
{
String myEol = System.getProperty("line.separator");
return new String("Style: " + style + myEol + "Color: " + color + myEol + "Size: " + size);
}
}
私はメインクラスで変数データを変更して出力するようにしています。今、私はオーバーロードされたコンストラクタの内部でそれを呼び出す方法しか知りませんが、データが初期化された値から変更された後に、どのように出力しますか?
私は、デフォルトと過負荷を使用していることがわかるように、メインクラスの例。私は
にpublic String toString()
{
String myEol = System.getProperty("line.separator");
return new String("Style: " + getStyle() + myEol + "Color: " + getColor() + myEol + "Size: " + getSize());
}
の代わりに、私はちょうど関数を呼び出し、変数自体を呼び出すことをそれを修正するために何をやったか
public class ShoeStore
{
public static void main(String[] args)
{
Shoes nerdShoes = new Shoes();
Shoes coolShoes = new Shoes("Sandals", "Brown", 8.5);
nerdShoes.setColor("Tan");
nerdShoes.setStyle("Walking");
nerdShoes.setSize(9.5);
System.out.println("The style of nerdShoes: " + nerdShoes.getStyle());
coolShoes.setColor("Purple");
System.out.println("The style of coolShoes: " + coolShoes.getStyle());
}
}
!どのように私はそれを逃したのか分からない。今それは正しく印刷されています!
を使用すると、データの変更、そのものとして、 'toString'メソッドが呼び出されることを意味するかプリントアウトでしょうか?その場合は、[プロパティー変更リスナー](https://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html)を作成する際のOracleチュートリアルを参照してください。 – Thomas
希望する効果を明確にする必要はありませんさあ。あなたは何を出力したいですか? – Andreas
もし私が正しいと分かったら。 'System.out.println(coolShoes.toString())' –