public class TestCar { public static void main(String[] args) { Car c = new Car(); c.info(); c.setName("凯迪拉克");// 通过方法来调的 c.setWheel(4); // 也可以通过属性来调用的 c.name = "保时捷"; c.wheel = 6; c.info(); } } class Car { String name; int wheel; public void info() { System.out.println("name:" + name + "wheel:" + wheel); } public void show() { System.out.println("一辆车"); } public void setName(String n) { name = n; } public void setWheel(int m) { wheel = m; } }
/* 定义一个Circle1类, 包含一个double型的radius属性代表圆的半径 一个findArea()方法返回圆的面积 定义一个PassObject,在类中定义一个方法printAreas(),该方法定义如下 printArea方法中打印输出1到time之间的整数半径值,以及对应的圆面积 在main方法调用printAreas()方法,调用完输出当前半径值 */ class Circle1 { double radius; public double findArea() { return Math.PI * radius * radius; // return Math.PI*getRadius()*getRadius(); } public void setRadius(double r) { radius = r; } public double getRadius() { return radius; } } public class PassObject { public static void main(String[] args) { PassObject p = new PassObject();// 通过p调用printArea()必须要有c1 那就造一个c1 Circle1 c2 = new Circle1();// 此时的c1的半径为0; p.printAreas(c2, 5); System.out.println("now radius is" + c2.getRadius()); } public void printAreas(Circle1 c1, int time) { System.out.println("Radius" + " " + "Area"); int temp = 0; for (int i = 1; i <= time; i++, temp = i) { c1.setRadius(i); System.out.println(c1.getRadius() + " " + c1.findArea()); } c1.setRadius(temp); } }
输出结果:
3.0 28.274333882308138
4.0 50.26548245743669
5.0 78.53981633974483
now radius is6.0