【解決方法】私のメイン コードでは、クラスで作成された変数が見つかりません。 これを修正するにはどうすればよいですか?


abstract class Shapes{
    public abstract double area();
    public abstract double perimeter ();
}
class Rectangle extends Shapes{
    private double width;
    private double length;
    public Rectangle(){
        this(1,1);
    }
    public Rectangle(double width, double length){
        this.width = width;
        this.length = length;
    }
    @ Override
    public double area(){
        return width * length;
    }
    @ Override
    public double perimeter(){
        return 2*(width + length);
    }
}


class Triangle extends Shapes{
    double a;
    double b;
    double c;
    public Triangle(){
        this(1,1,1);
    }
    public Triangle (double a, double b, double c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    @ Override
    public double area(){
        double s = (a+b+c)/2;
        return Math.sqrt(s*(s-a)*(s-b)*(s-c));
    }
    @ Override
    public double perimeter(){
        return a+ b + c;
    }
}
class Square extends Rectangle{
    Square s = new Square(50d);
    double area = s.area();
    double perimeter = s.perimeter();
}

public class Main
{
	public static void main(String[] args) {
	    width = 10;
	    length = 25;
	    Shapes Rectangle = new Rectangle (width, length);
	    System.out.println("The area of the rectangle is: " + Rectangle.area());
}
}

私が試したこと:

私はJavaでの継承に少し慣れていません。現在、クラスで作成した変数がメインコードで見つからないという問題があります。 長方形クラスの変数をプライベートにしようとしましたが、うまくいきませんでした。 どうすればいいですか?

解決策 1

交換

見積もり:

public class Square extends Rectangle{
正方形 s = 新しい正方形 (50d);
ダブルエリア = s.area();
double perimeter = s.perimeter();
}

公開クラス メイン
{
public static void main(文字列[] 引数) {
幅 = 10;
長さ = 25;
Shapes Rectangle = new Rectangle (幅、長さ);
System.out.println(“長方形の面積: ” + Rectangle.area());
}
}

Java
class Square extends Rectangle
{
    public Square(int a){ super(a,a); }
}

public class Main
{
  public static void main(String[] args) 
  {
      int width = 10;
      int length = 25;
      Shapes rectangle = new Rectangle (width, length);
      Shapes square = new Square(width);
      System.out.println("The area of the rectangle is: " + rectangle.area());
      System.out.println("The area of the square is: " + square.area());

      int a = 12;
      int b = 20;
      int c = 15;

      Shapes triangle = new Triangle(a,b,c);
      System.out.println("The area of the triangle is: " + triangle.area());
      System.out.println("The perimeter of the triangle is: " + triangle.perimeter());

  }
}

解決策 2

これは、この問題に関する 3 番目の質問です。 で時間を過ごすことをお勧めします Java チュートリアルのラーニング パス[^].

コメント

タイトルとURLをコピーしました