第九周上机练习
1、定义一个点类Point,包含2个成员变量x、y分
别表示x和y坐标,2个构造器Point()和Point(int
x0,y0),以及一个movePoint(int dx,int dy)方法实
现点的位置移动,创建两个Point对象p1、p2,分
别调用movePoint方法后,打印p1和p2的坐标。[
必作题]
package test; public class Point { private int x0; private int y0; public Point(){ } public Point(int x0,int y0){ this.x0=x0; this.y0=y0; } public void movePoint(int dx,int dy){ this.x0=this.x0+dx; this.y0=this.y0+dy; System.out.println("坐标为: "+x0+","+y0); }
public static void main(String[] args) {
Point p1=new Point();
Point p2=new Point();
p1.movePoint(6, 3);
p2.movePoint(5,8);
}
}

2、定义一个矩形类Rectangle:(知识点:对象的
创建和使用)[必做题]
• 2.1 定义三个方法:getArea()求面积、getPer()求
周长,showAll()分别在控制台输出长、宽、面积
、周长。
• 2.2 有2个属性:长length、宽width
• 2.3 通过构造方法Rectangle(int width, int length),
分别给两个属性赋值
• 2.4 创建一个Rectangle对象,并输出相关信息
package test; public class Rectangle { int width; int length; public Rectangle(int width,int length) { this.width=width; this.length=length; } public double getArea(){ return this.width*this.length; } public double getPer(){ return 2*(this.width+this.length); } public void showAll(){ System.out.println("宽="+this.width); System.out.println("长="+this.length); System.out.println("面积="+this.getArea()); System.out.println("周长="+this.getPer()); } public static void main(String[] args) { Rectangle r1=new Rectangle(5,8); r1.showAll(); } }

• 3、定义一个笔记本类,该类有颜色(char)和cpu
型号(int)两个属性。 [必做题]
• 3.1 无参和有参的两个构造方法;有参构造方法可
以在创建对象的同时为每个属性赋值;
• 3.2 输出笔记本信息的方法
• 3.3 然后编写一个测试类,测试笔记本类的各个
方法。
package test; public class Computer { char color; int cpu; public Computer() { color='白'; cpu=99; } public Computer(char color,int cpu) { this.color=color; this.cpu=cpu; } public void showAll() { System.out.println("笔记本颜色: "+color); System.out.println("笔记本的cpu型号: "+cpu); } public static void main(String[] args) { Computer c1=new Computer(); c1.showAll(); Computer c2=new Computer('黑',32); c2.showAll(); } }

6、定义两个类,描述如下: [必做题]
• 6.1定义一个人类Person:
• 6.1.1定义一个方法sayHello(),可以向对方发出
问候语“hello,my name is XXX”
• 6.1.2有三个属性:名字、身高、年龄
• 6.1.3通过构造方法,分别给三个属性赋值
• 6.2定义一个Constructor类:
• 6.2.1创建两个对象,分别是zhangsan,33岁,
1.73;lishi,44,1.74
• 6.2.2分别调用对象的sayHello()方法。
package test; public class Person { String name; int age; double sg; public Person(String name,int age,double sg) { this.name=name; this.age=age; this.sg=sg; } public void sayHello() { System.out.println("Hello,my name is "+name); System.out.println("My age is "+age); System.out.println("My height is "+sg); } }
package test; public class Constructor { public static void main(String[] args) { Person p1=new Person("zhangsan",33,1.73); Person p2=new Person("lisi",44,1.74); p1.sayHello(); p2.sayHello(); } }


浙公网安备 33010602011771号