Java作业,类的相关操作:定义圆类、矩形类,并实例化对象
import java.util.Scanner;
//圆类
class Circle {
//定义圆类的私有属性radius
private float radius;
//无参构造方法
Circle() {
radius = 0;
}
//带参构造方法
Circle(float radius) {
this.radius = radius;
}
//获取radius的值并返回
public float getRadius() {
return radius;
}
//修改私有属性radius的值
public void setRadius(float radius) {
this.radius = radius;
}
//计算圆的面积并返回
public double getArea() {
return radius * radius * Math.PI;
}
//计算圆的周长并返回
public double getPerimeter() {
return radius * Math.PI * 2;
}
}
//矩形类
class Rectangle {
//定义矩形类的私有属性:长和宽
private float length;
private float width;
//无参构造方法
Rectangle() {
length = 0;
width = 0;
}
//带参构造方法
Rectangle(float length, float width) {
this.length = length;
this.width = width;
}
//获取length的值并返回
public float getLength() {
return length;
}
//修改私有属性length的值
public void setLength(float length) {
this.length = length;
}
//获取width的值并返回
public float getWidth() {
return width;
}
//修改私有属性width的值
public void setWidth(float width) {
this.width = width;
}
//计算矩形的面积并返回
public double getArea() {
return width * length;
}
//计算矩形的周长并返回
public double getPerimeter() {
return (width + length) * 2;
}
}
//测试类
public class Graph {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//圆类实例化
Circle c = new Circle();
//调用类的成员方法 setRadius 修改半径 radius 的值
System.out.println("\n请输入圆的半径:");
c.setRadius(sc.nextFloat());
System.out.println("半径为:" + c.getRadius() + "的圆的面积为:" + c.getArea());
System.out.println("半径为:" + c.getRadius() + "的圆的周长为:" + c.getPerimeter());
//矩形类实例化
Rectangle r = new Rectangle();
//调用 set 方法修改矩形长和宽的值
System.out.print("\n请输入矩形的长:");
r.setLength(sc.nextFloat());
System.out.print("请输入矩形的宽:");
r.setWidth(sc.nextFloat());
System.out.println("长为" + r.getLength() + "宽为" + r.getWidth() + "的矩形的面积为:" + r.getArea());
System.out.println("长为" + r.getLength() + "宽为" + r.getWidth() + "的矩形的周长为:" + r.getPerimeter());
}
}