アットウィキロゴ

クラスとオブジェクトの応用

★クラスとオブジェクトの応用

objectクラス
objectクラス…すべてのクラスのスーパークラス

instanceof
instanceof……オブジェクトが指定したオブジェクトかどうか調べる
boolean flag =cinstanceofX;←クラス名
            ↑オブジェクト名
指定したインタフェースをオブジェクトが実装しているかを調べることもできる
boolean flag =cinstanceofY;←インタフェース名
            ↑オブジェクト名
 
    サンプルプログラム
 
interface Cry {
   void cry();
}
 
class Cat implements Cry {
   public void cry() {
      System.out.println("にゃー");
   }
}
 
class Dog {
   public void cry(){
      System.out.println("わん");
   }
}
 
class CheckCry {
   public static void main(String[] args){
      Cat cat = new Cat();
      Dog dog = new Dog();
 
      if(cat instanceof Cry) {
         cat.cry();
      }
      if(dog instanceof Cry) {
        dog.cry();
      }
   }
}
 

■サンプルプログラム

//抽象クラス Figure
abstract class Figure {
   abstract void area();   // 面積
   abstract void around(); // 外周
   void measure() {
      area();
      around();
      System.out.println();
   }
}
// 抽象クラスのサブクラス Square
class Square extends Figure {
   double side;
   double height;
   Square(double s){  // コンストラクタ
      side = height = s;
   }
   Square(double s, double h) {  // コンストラクタのオーバーロード
      side = s;
      height = h;
  }
   void area() {   // 抽象メソッドのオーバーライド
      System.out.println("四角形の面積:" + (side*height));
   }
   void around() {   // 抽象メソッドのオーバーライド
      System.out.println("四角形の外周:" + (2*(side+height)));
   }
}
// 抽象クラスのサブクラス Circle
class Circle extends Figure {
   final double pi = 3.14;
   double radius;
   Circle(double r) { // コンストラクタ
      radius = r;
   }
   void area() {  // 抽象メソッドのオーバーライド
      System.out.println("円の面積" + (radius*radius*pi));
   }
   void around() {
      System.out.println("円の外周" + (2*radius*pi));
   }
}
class SizeFigure {
   public static void main(String[] args) {
      Figure fig1 = new Square(2.5);
      Figure fig2 = new Square(2.3,3.7);
      Figure fig3 = new Circle(3.6);
      fig1.measure();
      fig2.measure();
      fig3.measure();
   }
}
最終更新:2008年03月10日 23:40