// 親クラス Vehicle
class Vehicle {
// インスタンス変数
private String color;
// 親クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿
public Vehicle(String color) {
this.color = color;
}
// インスタンス変数ã®ã‚²ãƒƒã‚¿ãƒ¼ãƒ¡ã‚½ãƒƒãƒ‰
public String getColor() {
return color;
}
}
// åクラス Car
class Car extends Vehicle {
// インスタンス変数
private int speed;
// åクラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿
public Car(String color, int speed) {
// 親クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’明示的ã«å‘¼ã³å‡ºã™
super(color);
this.speed = speed;
}
// インスタンス変数ã®ã‚²ãƒƒã‚¿ãƒ¼ãƒ¡ã‚½ãƒƒãƒ‰
public int getSpeed() {
return speed;
}
}
// メインクラス
public class Main {
public static void main(String[] args) {
// Car クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã‚’作æˆ
Car myCar = new Car("Blue", 60);
// インスタンス変数ã®å€¤ã‚’å–å¾—ã—ã¦è¡¨ç¤º
System.out.println("Car Color: " + myCar.getColor());
System.out.println("Car Speed: " + myCar.getSpeed());
}
}
ã“ã®ã‚³ãƒ¼ãƒ‰ã§ã¯ã€Vehicle クラスãŒè¦ªã‚¯ãƒ©ã‚¹ã¨ã—ã¦ã€Car クラスãŒåクラスã¨ã—ã¦å®šç¾©ã•れã¦ã„ã¾ã™ã€‚Car クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿å†…ã§ã€super(color) を使用ã—ã¦è¦ªã‚¯ãƒ©ã‚¹ã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’明示的ã«å‘¼ã³å‡ºã—ã¦ã„ã¾ã™ã€‚ã“れã«ã‚ˆã‚Šã€Car クラス㯠Vehicle クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹å¤‰æ•°ã¨ãƒ¡ã‚½ãƒƒãƒ‰ã‚’継承ã—ã¾ã™ã€‚
明示的ãªã‚¹ãƒ¼ãƒ‘ークラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿å‘¼ã³å‡ºã—
Javaã§ã¯ã€ã‚µãƒ–クラス(åクラス)ã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ãŒå®Ÿè¡Œã•ã‚Œã‚‹éš›ã€æš—黙的ã«ã‚¹ãƒ¼ãƒ‘ークラス(親クラス)ã®ãƒ‡ãƒ•ォルトコンストラクタãŒå‘¼ã³å‡ºã•れã¾ã™ã€‚ãŸã ã—ã€ã‚‚ã—スーパークラスã«å¼•æ•°ã‚’æŒã¤ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ãŒå®šç¾©ã•れã¦ã„ã‚‹å ´åˆã€æ˜Žç¤ºçš„ã«ãã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’呼ã³å‡ºã™å¿…è¦ãŒã‚りã¾ã™ã€‚
以下ã«ã€å…·ä½“例を挙ã’ãªãŒã‚‰ã€Œæ˜Žç¤ºçš„ãªã‚¹ãƒ¼ãƒ‘ークラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿å‘¼ã³å‡ºã—ã€ã«ã¤ã„ã¦èª¬æ˜Žã—ã¾ã™ã€‚
// 親クラス
class Vehicle {
private String color;
// スーパークラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿
public Vehicle(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
// åクラス
class Car extends Vehicle {
private int speed;
// サブクラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿
public Car(String color, int speed) {
// スーパークラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’明示的ã«å‘¼ã³å‡ºã™
super(color);
this.speed = speed;
}
public int getSpeed() {
return speed;
}
}
// メインクラス
public class Main {
public static void main(String[] args) {
// Car クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹ã‚’作æˆ
Car myCar = new Car("Blue", 60);
// インスタンス変数ã®å€¤ã‚’å–å¾—ã—ã¦è¡¨ç¤º
System.out.println("Car Color: " + myCar.getColor());
System.out.println("Car Speed: " + myCar.getSpeed());
}
}
ã“ã®ä¾‹ã§ã¯ã€Vehicle クラスãŒè¦ªã‚¯ãƒ©ã‚¹ã¨ã—ã¦ã€Car クラスãŒåクラスã¨ã—ã¦å®šç¾©ã•れã¦ã„ã¾ã™ã€‚Car クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿å†…ã§ super(color) を使用ã—ã¦ã€Vehicle クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã‚’明示的ã«å‘¼ã³å‡ºã—ã¦ã„ã¾ã™ã€‚ã“れã«ã‚ˆã‚Šã€Car クラス㯠Vehicle クラスã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹å¤‰æ•°ã¨ãƒ¡ã‚½ãƒƒãƒ‰ã‚’継承ã—ã¾ã™ã€‚
注æ„点ã¨ã—ã¦ã€super æ–‡ã¯ã‚µãƒ–クラスã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã®å…ˆé ã§å‘¼ã³å‡ºã•れる必è¦ãŒã‚りã¾ã™ã€‚ãれ以å‰ã®ä½ç½®ã§å‘¼ã³å‡ºã™ã“ã¨ã¯ã§ãã¾ã›ã‚“。ã“ã®ã‚ˆã†ãªæ˜Žç¤ºçš„ãªå‘¼ã³å‡ºã—ã¯ã€è¦ªã‚¯ãƒ©ã‚¹ã®ã‚³ãƒ³ã‚¹ãƒˆãƒ©ã‚¯ã‚¿ã«åˆæœŸåŒ–処ç†ãŒã‚ã‚‹å ´åˆã‚„ã€è¦ªã‚¯ãƒ©ã‚¹ã®ãƒ‡ãƒ•ォルトコンストラクタãŒå˜åœ¨ã—ãªã„å ´åˆã«ç‰¹ã«é‡è¦ã§ã™ã€‚
「014 継承ã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント