0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javaを基本からまとめてみた【継承・オーバーライド】

Last updated at Posted at 2023-03-08

継承

  • 継承とは、既存のクラスをもとに変数やメソッドを追加したクラスを作ること
  • 継承関係にある親のクラスのことをスーパークラス、子のクラスをサブクラスという
    ⇨ 継承を使うとコーディングとメンテナンスが楽!
public class サブクラス名 extends スーパークラス名{
    処理
}
// 継承できるクラスは1つ
// コンストラクタは継承しない

image.png

design(設計クラス).java
public class Student extends Person{
  private int stuNo;

  public void setStuNo(int $){
    stuNo = $;
}
 public void displayStuNo(){
 System.out.println( "学籍番号" + stuNo);
 }
}
execution(実行用).java
public class StuSample {
	public static void main(String[] args) {
		Student stu = new Student();
//スーパークラスメソッド
      stu.setName ("Kenny");
         stu.display ();
//サブクラスのメソッド
        stu.setStuNo(1);
        stu.displayStuNo ();
	}
}

オーバーライド

  • サブクラスでスーパークラスのメソッドを再定義することオーバーライドという
    条件:『戻り値の型』、『メソッド名』、『引数の型』と数が全て同じ
Sample.java
//スーパークラス
class Person{
 void display(){
 }
}
//サブクラス
 class Student extends Person{
void display(){
  }
}
design(設計クラス).java
public class Student2 extends Person{
  private int stuNo;

  public void setStuNo(int $){
    stuNo = $;
}
 public void displayStuNo(){
 System.out.println( "学籍番号" + stuNo);
 }
}
execution(実行用).java
public class StuSample2 {
	public static void main(String[] args) {
		Student2 stu = new Student();
      stu.setName ("Kenny");
         stu.setStuNo(1);
         stu.displayStuNo ();
	}
}

参考サイト

継承のメリットやextendsの使い方を理解しよう【Java入門講座】4-1 継承
【初心者向け】Javaの継承とは?extendsの使い方をマスター!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?