类与对象(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,调用实例方法判断c1和c2是否相重叠。
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);}}
阅读全文
0 0
- 类与对象(1)
- 类与对象(1)
- 类与对象1
- 类与对象(1)
- 类与对象()
- 面向对象1 类与对象
- JAVA面向对象1:类与对象
- java类与对象(面向对象)
- 类与对象(1):补充
- Poedu_C++_Lesson03_1_20161223_类与对象(1)
- java 基础(类与对象1)
- 【java】类与对象(1)
- JAVA(七)java面向对象1-面向对象的概念,类与对象
- 类与对象试验1
- Java_log2000_类与对象1
- 类与对象(一)
- 类与对象(二)
- 类与对象(2)
- Json的序列化与反序列化
- 使用移动数组下标的方式实现增删改查
- Callable、FutureTask中阻塞超时返回的坑点
- 知乎上对理解阻塞非阻塞与同步异步的有趣解释
- 向量外积的应用
- 类与对象(1)
- Tomcat 源码阅读(五)解析请求ProtocolHandler
- 将<select>被选中项的值通过<a>链接的参数形式传递给后台的实现方法
- python编译过程和执行原理
- mybatis学习之路----动态sql之if条件判断各种使用方式
- 多线程之ReadWriteLock模拟缓存(九)
- shell变量
- 去噪
- CentOS6.8安装及各种坑