実現したいこと
スーパークラスのインスタンスにサブクラスのインスタンスを代入したい。
発生している問題・分からないこと
スーパークラスのインスタンスにサブクラスのインスタンスを代入できない
エラーメッセージ
error
1Exception in thread "main" java.lang.Error: Unresolved compilation problems: 2 型の不一致: FigureRectangle から Figure には変換できません 3 型の不一致: FigureSquare から Figure には変換できません 4 メソッド shape() は型 Figure で不可視です
該当のソースコード
java2_2
1package java2_2; 2import java.util.Random; 3import java.util.Scanner; 4 5import java2_1.Figure; 6 7public class Kadai2_6 { 8 9 public static void main(String[] args) { 10 Scanner scanner = new Scanner(System.in); 11 Random random = new Random(); 12 Figure[] figureArray = new Figure[3]; 13 String[] shapes = {"長方形", "正方形"}; 14 int shapeIndex; //0:長方形,1:正方形 15 int x, y, width, height; 16 17 for(int i = 0;i < 3;i++) { 18 shapeIndex = random.nextInt(2); 19 20 if(shapeIndex == 0) { 21 System.out.println(shapes[shapeIndex] + "を作成します"); 22 System.out.print(shapes[shapeIndex] + "のx座標を入力してください。>"); 23 x = scanner.nextInt(); 24 System.out.print(shapes[shapeIndex] + "のy座標を入力してください。>"); 25 y = scanner.nextInt(); 26 System.out.print(shapes[shapeIndex] + "の幅を入力してください。>"); 27 width = scanner.nextInt(); 28 System.out.print(shapes[shapeIndex] + "の高さを入力してください。>"); 29 height = scanner.nextInt(); 30 31 figureArray[i] = new FigureRectangle(x, y, width, height); 32 } 33 else { 34 System.out.println(shapes[shapeIndex] + "を作成します"); 35 System.out.print(shapes[shapeIndex] + "のx座標を入力してください。>"); 36 x = scanner.nextInt(); 37 System.out.print(shapes[shapeIndex] + "のy座標を入力してください。>"); 38 y = scanner.nextInt(); 39 System.out.print(shapes[shapeIndex] + "の幅を入力してください。>"); 40 width = scanner.nextInt(); 41 42 figureArray[i] = new FigureSquare(x, y, width); 43 } 44 } 45 46 System.out.println("shapeメソッドの呼び出し"); 47 for(Figure figure : figureArray) { 48 figure.shape(); 49 } 50 51 52 } 53 54} 55
Figure
1package java2_2; 2 3public abstract class Figure { 4 private double x; 5 private double y; 6 7 Figure(double x, double y){ 8 this.x = x; 9 this.y = y; 10 } 11 12 abstract void shape(); 13 14 public double getX() { 15 return x; 16 } 17 18 public double getY() { 19 return y; 20 } 21} 22
FigureRectangle
1package java2_2; 2 3public class FigureRectangle extends Figure { 4 private double width; 5 private double height; 6 7 FigureRectangle(double x, double y, double width, double height){ 8 super(x, y); 9 this.width = width; 10 this.height = height; 11 } 12 13 @Override 14 void shape() { 15 System.out.println("(" + super.getX() + "," + super.getY() + ")に幅" + width + "高さ" + height + "の長方形を描きます。"); 16 } 17} 18
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
同様の質問は見つからず。
補足
特になし
変数とインスタンスの違いはついたほうが良いと思います。
