上机10
1、请按照以下要求设计一个学生类Student,并进行测试。
要求如下:
1)Student类中包含姓名、成绩两个属性
2)分别给这两个属性定义两个方法,一个方法用于设置值,另一个方法用于获取值.
3)Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值
4)在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,一个使用有参的构 造方法,在构造方法中给姓名和成绩赋值
package ww; public class student { private String name; private int score; public student() { super(); } public student(String name, int score) { super(); this.name = name; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
package ww; public class test { public static void main(String[] args) { student s1 = new student(); student s2 = new student("张三", 91); s1.setName("李四"); System.out.println(s1.getName()); s1.setScore(98); System.out.println(s1.getScore()); System.out.println(s2.getName()); System.out.println(s2.getScore()); } }
2、请编写一个程序,该程序由两个类组成,一个Person类,一个Test类。在Person类中定义一个无参构造方法,里面 输出一句话:”无参的构造方法被调用了...”。并在测试类中进行测试。
package ww; public class Person { public Person() { System.out.println("无参的构造方法被调用了"); } }
package ww; public class Test { public static void main(String[] args){ Person a = new Person(); } }
3. 使用java类描述一个车类,车都具备名字、颜色两个属性,还具备跑的功能。 请设计一个汽车类Car,该类中包含 两个属性姓名(name)、颜色(color),一个用于描述汽车跑的run()方法。、
package ww; public class me { public static void main(String[] args) { car c = new car(); c.name = "五菱宏光"; c.color = "白色"; System.out.println("名字:"+ c.name+" 颜色:"+ c.color); c.run(); } }
package ww; public class car { String name; String color; public void run(){ System.out.println(name+"速度快"); } }
4. 编写一个类,类中定义一个静态方法,用于求两个整数的和。 请按照以下要求设计一个测试类Demo,并进行测试。 要求如下:
1)Demo类中有一个静态方法get(int a,int b)该方法用户返回参数a、b两个整数的和;
2)在main()方法中调用get方法并输出计算结果。
package ww; public class Demo { public static void main(String[] args) { Demo a = new Demo(); int c = a.get(1,2); System.out.println(c); } public int get(int a,int b) { return a+b; } }
5.说一下什么是封装, 使用封装的好处。什么是get,set访问器
封装,就是指把硅片上的电路管脚,用导线接引到外部接头处,以便于其它器件连接。封装形式是指安装半导体集成电路芯片用的外壳。它不仅起着安装、固定、密封、保护芯片及增强电热性能等方面的作用,而且还通过芯片上的接点用导线连接到封装外壳的引脚上,这些引脚又通过印刷电路板上的导线与其他器件相连接,从而实现内部芯片与外部电路的连接。
封装的好处 重用、不必关心具体的实现、面向对象三大特征之一、具有安全性
get访问器
public class AccessDemo {
private int readOnly;
private int writeOnly;
public int getReadOnly() {
return readOnly;
}
set访问器
public void setWriteOnly(int writeOnly) {
this.writeOnly = writeOnly;
}
}

浙公网安备 33010602011771号