誰かが次の式が何をするのか説明できますか?
System.out.println(((Window)this).size)
これがあるとしましょう:
System.out.println(this.size)
この式が何をするかは理解できますが、 が何をするかはわかりません。問題は、キーワード(Window)
の前の the の意味です(この例で使用するクラスのスーパークラスであると仮定しましょう)。(Window)
this
Window
誰かが次の式が何をするのか説明できますか?
System.out.println(((Window)this).size)
これがあるとしましょう:
System.out.println(this.size)
この式が何をするかは理解できますが、 が何をするかはわかりません。問題は、キーワード(Window)
の前の the の意味です(この例で使用するクラスのスーパークラスであると仮定しましょう)。(Window)
this
Window
The (Window) this
expression is casting the this
reference to the Window
class. A cast transforms an object reference from one class to another (related) class. For example, in Java, one frequently casts Graphics
objects to Graphics2D
objects, like so:
Graphics g;
Graphics2D g2d = (Graphics2D) g;
You are correct to think that Window
is a superclass of the relevant class; if it were an unrelated class, you would get a compile-time error.
Casting to a sub-class (as in the example above with graphics objects) can give you more capabilities. For example, the Graphics2D
object has methods that Graphics
objects do not (for example, fill
and setRenderingHint
).
It is type casting...
Like you do for casting an integer
to float
float b= (float)1;
一般的には意味がありません。
次のようなシナリオで役立つと思います。
class P {
protected String size = "P - Size";
}
class C extends P {
protected String size = "C - Size";
public void m() {
System.out.println(this.size);
System.out.println(((P)this).size);
}
public static void main(String... args) {
new C().m();
}
}
ここでの出力は次のとおりです。
C-サイズ P-サイズ
そのため、親のフィールドにアクセスするには、(それ自体の親への)明示的なキャストが必要でした。