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を基本からまとめてみた【this・super】

Last updated at Posted at 2023-03-08

①this と super によるメンバ変数・メソッドの呼び出し

this.~ = 自分のオブジェクトの~
super.~ = スーパークラスの~
メリット
  • 同じコードを書かなくて良い
  • 引数名を考えなくてもよい ⇨ プログラムを自動的に作成できるようになる
Sample.java
class Person {
String name ;
void setName(String name){
//thisキーワードを使うことによって引数の名前をメンバ変数の名前と合わせる
書き方ができる
this.name = name;
}
void display(){
System.out.println(this.name);
}
class Student extends Person {
ind stuNo;

//オーバーライド
void display(){
//super.display()でスーパークラスのdisplay()を読み出している
//⇨ 上書きする前の処理を呼び出してあげるという記述
super display();
System.out.println(stuNo);
}
}

②this と super によるコンストラクタの呼び出し

this (引数)は、同じクラスの中でコンストラクタを呼び出しあうことができる
super(引数)は、スーパークラスのコンストラクタを呼び出すことができる

※ this (引数)~,super(引数)はコンストラクタ内の先頭に記述する。
なければ自動的にsuper();が挿入される
this.java
class Person {
   String name;
   Person(){
    this.("未設定");
}
   Person(String name){
    this.name = name;
  }
}
super.java
class Student extends Person {
   int stuNO;
   
   Student(String name, intstuNo){
   super(name){
    this.stuNo = stuNo;
  }
}
Peson3.java
public class Person{
  private String name;

public Person3(String name) {
 this.name = neme;
}

public void display(){
  System.out.println("名前:" + name);
 }
}
Student3.java
public class Student3 extends Person3{
 private int stuNo;

public Student3(String name){
 this (name, 999);
}
public Student3(String name, int stuNo){
 super (name);
 hits.stuNo = stuNo;
}
public void display(){
  super.display();
  System.out.println("学籍番号:" + name);
 }
}
execution(実行用).java
public class StuSample3 {
	public static void main(String[] args) {
		Student3 stu = new Student("Kenny");
        stu.display();
	}
}

参考サイト

thisとsuperの使い方を初心者向けに解説【Java入門講座】4-3 thisとsuper

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?