Java第十二次作业
1.定义一个点类Point,包含两个成员变量x,y分别表示x和y坐标,2个构造器Point( )和Point(int x0,int y0),
以及一个movePoint(int dx,int dy)方法实现点的位置移动,创建两个Point对象p1、p2,分别调用movePoint
方法后,打印p1和p2的坐标。
1 package test; 2 3 public class Point { 4 int x; 5 int y; 6 7 public Point() { 8 super(); 9 } 10 11 public Point(int x0, int y0) { 12 super(); 13 this.x = x0; 14 this.y = y0; 15 } 16 17 public void movePoint(int dx, int dy) { 18 this.x += dx; 19 this.y += dy; 20 } 21 22 public static void main(String[] args) { 23 Point p1 = new Point(1, 2); 24 p1.movePoint(3, 4); 25 System.out.println("p1:(" + p1.x + "," + p1.y + ")"); 26 Point p2 = new Point(5, 6); 27 p2.movePoint(7, 8); 28 System.out.println("p2:(" + p2.x + "," + p2.y + ")"); 29 } 30 }
2.、定义一个矩形类Rectangle: (知识点: 对象的创建和使用)[必做题]
2.1 定义三个方法: getArea(求面积、getPer0求周长,showAll0分 别在控制台输出长、宽、面积周长。
2.2 有2个属性:长length、 宽width
2.3 通过构造方法Rectangle(int width, int length),分别给两个属性赋值
2.4 创建-个Rectangle对象, 并输出相关信息
1 package test; 2 3 public class Rectangle { 4 int length; 5 int width; 6 7 public Rectangle(int length, int width) { 8 super(); 9 this.length = length; 10 this.width = width; 11 } 12 13 public int getArea() { 14 return length * width; 15 } 16 17 public int getPer() { 18 return (length + width) * 2; 19 } 20 21 public void showAll() { 22 System.out.println("长:" + length + "宽:" + width + "面积:" + getArea() + "周长:" + getPer()); 23 } 24 25 public static void main(String[] args) { 26 Rectangle R1 = new Rectangle(2, 4); 27 R1.showAll(); 28 } 29 }
3、定义一-个笔记本类,该类有颜色(char) 和cpu型号(int) 两个属性。[必做题]
3.1无参和有参的两个构造方法;有参构造方法可以在创建对象的同时为每个属性赋值;
3.2 输出笔记本信息的方法
3.3 然后编写一-个测试类,测试笔记本类的各个方法。
1 package test; 2 3 public class NotBook { 4 char color; 5 int model; 6 7 public NotBook(char color, int model) { 8 super(); 9 this.color = color; 10 this.model = model; 11 } 12 13 public NotBook() { 14 super(); 15 } 16 17 public void show() { 18 System.out.println("笔记本的型号是:" + model + ",颜色是:" + color); 19 } 20 21 }
1 package test; 2 3 public class NotBookTest { 4 public static void main(String[] args) { 5 NotBook B1 = new NotBook('黑', 12345); 6 NotBook B2 = new NotBook(); 7 B2.model = 54321; 8 B2.color = '白'; 9 B1.show(); 10 B2.show(); 11 } 12 }