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 3 years have passed since last update.

Java superキーワード

Posted at

1,superキーワードとは

スーパークラス(親クラス)のオブジェクトを参照するキーワードです。

2,ソースコード

Main.java
public class Main {

	public static void main(String[] args) {

		// super = keyword refers to the superclass (parent) of an object
		//         very similar to the "this" keyword

		Hero hero1 = new Hero("Batman", 42, "$$$");
		Hero hero2 = new Hero("Superman", 43, "everything");

		System.out.println(hero1.name);
		System.out.println(hero1.age);
		System.out.println(hero1.power);

		System.out.println(hero2.toString());

	}

}

Personクラス(スーパークラス)👇

Person.java
public class Person {

	String name;
	int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return this.name + "\n" + this.age + "\n";
	}

}

Personクラスを継承しているHeroクラス👇

Hero.java
public class Hero extends Person {

	String power;

	public Hero(String name, int age, String power) {
		super(name, age);

		this.power = power;
	}

	public String toString() {
		return super.toString() + this.power;
	}
}
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?