Java p n class Vector double x double
Javaによるオブジェクト指向 (クラス) p クラスは,インスタンス変数とメソッドをカプセル化したもの. n 例: class Vector { double x; double y; Vector add(Vector a) { x += a. x; y += a. y; return this; } double inner_product(Vector a) { return x * a. x + y * a. y; } double length() { return Math. sqrt(inner_product(this)); } } インスタンス変数 メソッド
Javaによるオブジェクト指向 (this演算子) p this演算子: 自分自身を参照する演算子. n 例: class Vector { double x; double y; Vector add(Vector a) { x this. x += a. x; y this. y += a. y; return this; } double inner_product(Vector a) { return x this. x * a. x* + a. x y* + a. y; this. y * a. y; } double length() { return Math. sqrt(this. inner_product(this)); Math. sqrt(inner_product(this)); } }
Javaによるオブジェクト指向 (継承) p extends キーワードを使って継承する. n n 拡張するインスタンス変数,メソッドのみ定義する. 例: class Vector 3 D extends Vector { 拡張するメンバ変数 double z; Vector add(Vector a) { x += a. x; y += a. y; z += a. z; 置き換える return this; メソッド } double inner_product(Vector a) { 拡張する return x * a. x + y * a. y + z * a. z; メソッド } Vector 3 D outer_product(Vector 3 D a) { return new Vector 3 D(y*a. z - z*a. y, z*a. x - x*a. z, x*a. y - y*a. x); } }
Javaによるオブジェクト指向 (オーバーライド) p オーバーライド: 継承によるメソッドの置き換え. n Vector 3 Dでは,addと inner_productをオーバーライド している. double x; double y; Vector add(Vector a); double inner_product(Vector a); double length(); Vector 3 D double z; Vector add(Vector a); double inner_product(Vector a); Vector 3 D outer_product(Vector 3 D a);
Javaによるオブジェクト指向 (継承とメソッド呼出し) p メソッド呼出しの例: class Test { public static void main(String args[]) { Vector a = new Vector(5, 10); Vector b = new Vector(15, 20); Vector 3 D c = new Vector 3 D(5, 10, 15); Vector 3 D d = new Vector 3 D(20, 25, 30); System. out. println(a. inner_product(b)); Vectorの System. out. println(c. inner_product(d)); Vector 3 Dの System. out. println(a. length()); Vectorの System. out. println(c. length()); Vectorの a = a. outer_product(b); エラー!! c = c. outer_product(d); Vector 3 Dの } } →変数の型宣言だけを見て呼出し先がわかることに注意!!
- Slides: 13