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