第十周上机练习内容:
1、请按照以下要求设计一个学生类Student,并进行测试。
要求如下:
1)Student类中包含姓名、成绩两个属性
2)分别给这两个属性定义两个方法,一个方法用于设置值,另一个方法用于获取值.
3)Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值
4)在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,一个使用有参的构 造方法,在构造方法中给姓名和成绩赋值
1 package Student; 2 3 public class Constructor { 4 public static void main(String[] args) { 5 Student p1 = new Student(); 6 p1.set("zhangsan", 99); 7 p1.get(); 8 Student p2 = new Student("lisi", 77); 9 p2.get(); 10 } 11 } 12 13 package Student; 14 15 public class Student { 16 double achievement; 17 public String name; 18 19 public Student() { 20 } 21 22 public Student(String name, double achievement) { 23 this.name = name; 24 this.achievement = achievement; 25 } 26 27 void set(String name, double achievement) { 28 this.name = name; 29 this.achievement = achievement; 30 } 31 32 void get() { 33 System.out.println("该学生的名字为:" + name); 34 System.out.println("该学生的成绩为" + achievement); 35 } 36 }
2、请编写一个程序,该程序由两个类组成,一个Person类,一个Test类。在Person类中定义一个无参构造方法,里面 输出一句话:”无参的构造方法被调用了...”。并在测试类中进行测试。
package Student; public class Test { public static void main(String[] args) { Person p1 = new Person(); } } package Student; public class Person { public String name; private int age; public Person() { System.out.println("无参的方法已经被调用。。"); } }
3. 使用java类描述一个车类,车都具备名字、颜色两个属性,还具备跑的功能。 请设计一个汽车类Car,该类中包含 两个属性姓名(name)、颜色(color),一个用于描述汽车跑的run()方法。
1 package Student; 2 3 public class Car { 4 public String name; 5 public String color; 6 7 public Car() { 8 9 } 10 11 public Car(String name, String color) { 12 this.name = name; 13 this.color = name; 14 run(); 15 } 16 17 public void showAll() { 18 System.out.println(name + "的颜色是" + color); 19 } 20 21 public void run() { 22 System.out.println(name + "跑的方式是半自动"); 23 } 24 25 public static void main(String[] args) { 26 Car p1 = new Car("路虎揽胜星脉", "黑色"); 27 Car p2 = new Car("玛莎拉蒂GT", "黑色"); 28 } 29 }
4. 编写一个类,类中定义一个静态方法,用于求两个整数的和。 请按照以下要求设计一个测试类Demo,并进行测试。 要求如下:
1)Demo类中有一个静态方法get(int a,int b)该方法用户返回参数a、b两个整数的和;
2)在main()方法中调用get方法并输出计算结果。
package Student; public class Demo { public static int get(int a, int b) { return a + b; } public static void main(String[] args) { int a = 10; int b = 10; System.out.println(get(a, b)); } }
5.说一下什么是封装, 使用封装的好处。什么是get,set访问器
封装是只能在该类情况下调用此属性
封装可以将数据保护起来,更安全
set访问器是通该方法,将封装的属性赋值
get访问器,是得到封装属性返回的值