类与对象(1)

来源:互联网 发布:呱呱漫画软件 编辑:程序博客网 时间:2024/06/12 15:16

课堂练习1

请定义一个交通工具(Vehicle)的类,其中有:

Ø 属性:速度(speed),体积(size)等

Ø 方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等

在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。

public class Vehicle {int speed;int size;void move() {}void setSpeed(int speed){this.speed=speed;System.out.println("速度是:"+speed);}int getSpeed() {return speed;}void setSize(int size) {this.size=size;System.out.println("体积是:"+size);}int getSize() {return size;}int speedUp() {speed=speed+20;return speed;}int speedDown() {speed=speed-20;return speed;}public static void main(String[] args) {Vehicle vehicle=new Vehicle();vehicle.setSpeed(100); vehicle.setSize(80); System.out.println("加速后是:"+vehicle.speedUp()); System.out.println("减速后是:"+vehicle.speedDown());}}


课堂练习2

打印当前时间。学习使用Date类和Calendar类。

import java.util.Calendar;import java.util.Date;public class Time {public static void main(String[] args) {Calendar time =Calendar.getInstance();    Date date=new Date();    time.setTime(date);    int year=time.get(Calendar.YEAR),    month=time.get(Calendar.MONTH)+1,    day=time.get(Calendar.DAY_OF_MONTH);    int hour=time.get(Calendar.HOUR_OF_DAY),         minute=time.get(Calendar.MINUTE),         second=time.get(Calendar.SECOND);     System.out.println("当前的时间是:"+year+"年"+" "+month+"月"+day+"日"         +hour+"时"+" "+minute+"分"+" "+second+"秒"+" ");    }}



 

课堂练习3

Point基础,定义一个平面中的Circle类

1、 编写一个无参的构造函数

2、 编写一个有参的构造函数

主函数中调用无参的构造函数生成圆的实例c1,调用有参的构造函数生成圆的实例c2,调用实例方法判断c1c2是否相重叠。

public class Point {    int x,y,r;public Point() { x=4; y=4; r=2; System.out.println("C1的横坐标是:"+x+",C1的纵坐标是:"+y+"半径是:"+r); } public Point(int x, int y, int r) { this.x = x; this.y = y; this.r = r; System.out.println("C2的横坐标是:"+x+",C1的纵坐标是:"+y+"半径是:"+r); } public void testPoint(Point c) { if(c.x==x&&c.y==y&&c.r==r) { System.out.println("c1与c2重叠"); }else { System.out.println("c1与c2不重叠"); } } public static void main(String[] args) {     Point c1=new Point();    Point c2=new Point(4,1,5);    c1.testPoint(c2);}}