アットウィキロゴ

クラスの継承

★クラスの便利な機能
継承
スーパークラス(親クラス)…メンバを定義

サブクラス(子クラス)………スーパークラスの持っているメンバを継承できる

継承できないメンバ
private修飾子の記述(継承の制限、フィールドやメソッドの利用制限)

★継承の定義


■継承の定義
extendsを使ってサブクラスを作成する。
Class Animal {
String name;
int age;
 
void print() {
}
}
↓継承(extends)サブクラス名extendsスーパークラス名
ClassCatextendsAnimal{
int birth;
}
 
class pet {
public static void main(String[] args) {
Cat cat = new Cat();
}
}
■サンプルプログラム

class Book {
   String title;
   String genre;

   void printBook() {
      System.out.println("タイトル:" + title);
      System.out.println("ジャンル:" + genre);
   }
}

class Novel extends Book {
   String writer;

   void printNov(){
      printBook();
      System.out.println("著  者:" + writer);
   }
}

class Magazine extends Book {
   int day;

   void printMag(){
      printBook();
      System.out.println("発 売 日:" + day + "日");
   }
}

class Bookshelf {
   public static void main(String[] args) {
      Novel nov = new Novel();
      nov.title = "しおりの大冒険";
      nov.genre = "ファンタジー";
      nov.writer = "アンク";
      Magazine mag = new Magazine();
      mag.title = "月刊Javaの絵本";
      mag.genre = "コンピュータ";
      mag.day = 20;
      nov.printNov();
      System.out.println();
      mag.printMag();
   }
}

 
最終更新:2008年03月07日 20:48