对象
package calcu;
public class calcu {
public int plus(int a,int b){
return a+b;
}
public double plus(double a, double b){
return a+b;
}
public int cheng(int a, int b){
return a*b;
}
public int jian(int a,int b){
return a-b;
}
public double chu(double a , double b){
return a/b;
}
}
package calcu;
public class Test {
public static void main(String[] args) {
calcu c = new calcu();
System.out.println(c.plus(1,2));
System.out.println(c.plus(1,3));
System.out.println(c.cheng(1,3));
}
}
请定义一个交通工具(Vehicle)的类其中有:
属性: 速度(speed)、 体积(size)等,方法:移动(move())、设置速度(setSpeed(int speed))、加速 speedUp()、减速 speedDown()等。
最后在测试类 Vehicle 中的 main()中实例化一个交通工具对象并通过方法给它初始化 speed,size 的值并且通过打印出来。
另外调用加速、减速的方法对速度进行改变。
package calcu;
public class Vehicle {
public int speed;
public int size;
public void move(){
System.out.println("speed="+speed+" size="+size);
}
public void setSpeed(int speed){
this.speed = speed;
}
public void speedUp(){
this.speed+=10;
System.out.println("speed="+speed);
}
public void speedDown(){
this.speed-=10;
System.out.println("speed="+speed);
}
}
package calcu;
public class Test {
public static void main(String[] args) {
Vehicle su = new Vehicle();
su.speed = 90;
su.size = 120;
su.move();
su.setSpeed(50);
su.move();
su.speedDown();
su.speedUp();
}
}
speed=90 size=120
speed=50 size=120
speed=40
speed=50
定义一个圆类——Circle,在类的内部提供一个属性:
半径,同时 提供 两个 方 法 : 计算 面积 ( getArea() ) 和 计算 周长(getPerimeter()) 。
通过两个方法计算圆的周长和面积并且对计算结果进行输出。最后定义一个测试类对 Circle 类进行使用。
package calcu;
import java.lang.Math;
public class Circle {
double r;
public double getArea(double R){
System.out.println("Area = "+Math.PI*R*R);
return Math.PI*R*R;
}
public double getPerimemter(double R){
System.out.println("C = "+R*2*Math.PI);
return R*2*Math.PI;
}
}
package calcu;
public class Test {
public static void main(String[] args) {
Circle r = new Circle();
r.r = 1;
r.getArea(1);
r.getPerimemter(1);
}
}
Area = 3.141592653589793
C = 6.283185307179586