gpt4 book ai didi

java - Java 中的类变量和类方法,我的错

转载 作者:行者123 更新时间:2023-12-01 09:50:27 25 4
gpt4 key购买 nike

类;

package com.eteration.model;

public class Circle {
private static double PI;
private int radius;
private double area;

public double calculateArea(){
return radius*radius*PI;
}

public static double getPI() {
return PI;
}

public static void setPI(double pI) {
PI = pI;
}

public int getRadius() {
return radius;
}

public void setRadius(int radius) {
this.radius = radius;
}

public double getArea() {
return area;
}

public void setArea(double area) {
this.area = area;
}

}

剪贴簿;

Circle.PI=3.14;
System.out.println(Circle.getPI());
Circle circle1=new Circle(7);
System.out.println(circle1.getPI());
circle1.PI=3.1415;
Circle circle2=new Circle(3);
System.out.println(circle1.getPI());
System.out.println(circle2.getPI());
circle2.setPI(3.141592);
System.out.println(circle1.getPI());
System.out.println(circle2.getPI());
System.out.println(Circle.getPI());

我正在尝试锻炼。在本练习中,我在将示例编码到剪贴簿后创建了一个类。但是,我看到了错误。这些错误; “Circle 无法重新分配给变量,无法解析 Circle,无法解析 Circle 的类型。”帮助我。

最佳答案

你不能这样做Circle Circle1=new Circle(7); 因为您没有为采用整数的类 Circle 定义构造函数......

我会修改类来改进它,如下所示:

  • 将常量PI公开,并删除setter和getter,您将能够像Circle.PI一样访问它

    class Circle {
    public static double PI = 3.1415927;
    private int radius;
    private double area;

    public double calculateArea() {
    return radius * radius * PI;
    }

    public Circle(int radius) {
    this.radius = radius;
    }

    public int getRadius() {
    return radius;
    }

    public void setRadius(int radius) {
    this.radius = radius;
    }

    public double getArea() {
    return area;
    }

    public void setArea(double area) {
    this.area = area;
    }
    }
<小时/>

之后剪贴簿将如下所示:

类;

包 com.eteration.model;

公共(public)课圈子{ 私有(private)静态双PI; 私有(private) int 半径; 私有(private)双区域;

public double calculateArea(){
return radius*radius*PI;
}

public static double getPI() {
return PI;
}

public static void setPI(double pI) {
PI = pI;
}

public int getRadius() {
return radius;
}

public void setRadius(int radius) {
this.radius = radius;
}

public double getArea() {
return area;
}

public void setArea(double area) {
this.area = area;
}

}剪贴簿;

//Circle.PI=3.14; // dont need this
System.out.println(Circle.PI ); // instead of getPI()
Circle circle1 = new Circle(7); //the same
//System.out.println(circle1.getPI()); //dont need it since is a class constant
//circle1.PI=3.1415; // dont need it
Circle circle2=new Circle(3); //ok
System.out.println(circle1.getPI());//dont need it
System.out.println(circle2.getPI());//dont need it
circle2.setPI(3.141592);//dont need it
System.out.println(circle1.getPI());//dont need it
System.out.println(circle2.getPI());//dont need it
System.out.println(Circle.getPI());//dont need it

关于java - Java 中的类变量和类方法,我的错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com