// Person クラスã®å®šç¾©
class Person {
// introduce メソッド
public void introduce() {
System.out.println("I am a person.");
}
}
// Student クラスã®å®šç¾©ï¼ˆPerson クラスを継承)
class Student extends Person {
// introduce メソッドをオーãƒãƒ¼ãƒ©ã‚¤ãƒ‰
@Override
public void introduce() {
System.out.println("I am a student.");
}
}
// Teacher クラスã®å®šç¾©ï¼ˆPerson クラスを継承)
class Teacher extends Person {
// introduce メソッドをオーãƒãƒ¼ãƒ©ã‚¤ãƒ‰
@Override
public void introduce() {
System.out.println("I am a teacher.");
}
}
// メインクラス
public class Main {
public static void main(String[] args) {
// Person クラス型ã®å‹•çš„ãªé…列を作æˆ
Person[] people = new Person[3];
// ç•°ãªã‚‹äººç‰©ã®ã‚ªãƒ–ジェクトをé…åˆ—ã«æ ¼ç´
people[0] = new Person();
people[1] = new Student();
people[2] = new Teacher();
// é…列をイテレートã—ã¦å„オブジェクトãŒã©ã®ã‚¯ãƒ©ã‚¹ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã§ã‚ã‚‹ã‹ã‚’確èª
for (Person person : people) {
// Person クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã§ã‚ã‚‹ã‹ã‚’確èª
if (person instanceof Person) {
System.out.println("This is an instance of Person");
}
// Student クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã§ã‚ã‚‹ã‹ã‚’確èª
if (person instanceof Student) {
System.out.println("This is an instance of Student");
}
// Teacher クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã§ã‚ã‚‹ã‹ã‚’確èª
if (person instanceof Teacher) {
System.out.println("This is an instance of Teacher");
}
// å„オブジェクト㮠introduce メソッドを呼ã³å‡ºã—
person.introduce();
// 区切りã®å‡ºåŠ›
System.out.println("----------------------");
}
}
}
ã“ã®ãƒ—ãƒã‚°ãƒ©ãƒ ã§ã¯ã€Personクラス型ã®å‹•çš„ãªé…列を作æˆã—ã€ãã®ä¸ã«ç•°ãªã‚‹äººç‰©ã®ã‚ªãƒ–ã‚¸ã‚§ã‚¯ãƒˆã‚’æ ¼ç´ã—ã¦ã„ã¾ã™ã€‚ãã—ã¦ã€é…列をイテレートã—ã¦å„オブジェクトãŒã©ã®ã‚¯ãƒ©ã‚¹ã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã§ã‚ã‚‹ã‹ã‚’確èªã—ã€introduceメソッドを呼ã³å‡ºã—ã¦ã„ã¾ã™ã€‚
å®Ÿè¡Œçµæžœï¼š
This is an instance of Person
I am a person.
----------------------
This is an instance of Person
This is an instance of Student
I am a student.
----------------------
This is an instance of Person
This is an instance of Teacher
I am a teacher.
----------------------
「015 ãƒãƒªãƒ¢ãƒ¼ãƒ•ィズムã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント