栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

TestCircle.java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

TestCircle.java

       定义Circle类并使用该类创建对象。构造三个圆对象,其半径分别为1,25和125,然后显示这三个圆的半径和面积。接着将第二个对象的半径改为100,并显示新的半径和面积。


public class TestCircle {
  public static void main(String[] args) {
    Circle circle1 = new Circle(1);
    System.out.println("The area of the circle of radius " + circle1.radius + " is " + 
    circle1.getArea());
    Circle circle2 = new Circle(25);
    System.out.println("The area of the circle of radius " + circle2.radius + " is " + 
    circle2.getArea());
    Circle circle3 = new Circle(125);
    System.out.println("The area of the circle of radius " + circle3.radius + " is " + 
    circle3.getArea());
    circle2.radius = 100;
    System.out.println("The area of the circle of radius " + circle2.radius + " is " + 
    circle2.getArea());
    }
}
class Circle {
  double radius;
  Circle() {
  }
  Circle(double radius) {
  this.radius = radius;
  }
  double getArea() {
  return radius*radius*Math.PI;
  }
  double getPerimeter() {
  return 2*radius*Math.PI;
  }
  void setRadius(double radius) {
  this.radius = radius;
  }
} 

1.使用new操作符从构造方法创建一个对象:new Circle(1)创建一个半径为1的对象(第3行)

创建对象:类名 对象名 = new 类名()

2.getArea()方法计算它们各自的面积

3.使用circle1.radius通过对象引用来访问数据域

4.使用circle1.getArea()通过引用来调用方法

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/820314.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号