第6章习题
1.
- 如果一个java源文件中的包语句是“package java.chan”,则,编译后的字节码文件应该保存在哪里?其它包中的类应该如何使用该包中的类?
- 答:
(1)编译后的字节码文件保存在…/java/chan件夹中
(2)其它包中的类使用语句:import java.chan;就可以使用这个包
2.类的2种可见性有什么区别?类成员的4种可见性有什么区别?
- 答:
1)类的两种可见性是:包级别和public级别
(1)任何包中的类都可以实例化public级别的类;
(2)与包级别的类在同一包中的类才可以实例化包级别的类 ;
2)类成员的可见性有四种 ,从低到高的顺序是:private、包级别、protected和public
private :可见性范围是本类;
包级别: 可见性范围是本包;
protected :可见性范围是本包和子类;
public :任何包中的类都可见;
3.
- 请定义一个名为Rectangle的矩形类。其属性分别是:宽(width)、高(height)和颜色(color)。width和height的数据类型是float,color的数据类型是String。假定所有矩形的颜色相同。要求定义计算矩形面积的方法(getArea())。
class Rectangle{
private float w, h;
static public String c = "black";
Rectangle(float w, float h){
this.w = w;
this.h = h;
}
public float getArea(){
return w*h;
}
4.
- 定义人类(People)和羊类(Sheep)。要求为每个属性提供访问器方法。
class People{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Sheep{
private int age;
public int getAge(){
return age;
}
public void setAge(){
this.age = age;
}
}
5.举例说明成员变量与局部变量的区别、类变量与实例变量的区别、类方法与实例方法的区别。
public class VariableDiff {
int instanceVariable;
static int classVariable;
public void instanceMethod() {
int localVariable;
System.out.println(instanceVariable);
System.out.println(classVariable);
}
public void instanceMethod02() {
instanceMethod();
classMethod();
}
public static void classMethod() {
System.out.println(classVariable);
}
public static void main(String[] args) {
classMethod();
}
}
- 编写一个满足下列要求的程序:
定义学生类类,属性分别是:姓名(name,String)、学号 (ID,int)和年级(state,int,1:新生,2:二年级,3:三年级,4:四年级)。
创建30个学生,学生的姓名、学号、年级通过键盘输入。
查找二年级的学生人数,并输出姓名和学号。
答:代码见Unit6 u6q6
private static void u6q6(){
int n=30;
Student shool[] = new Student[n];
while(Student.count != n )
shool[Student.count] = new Student();
System.out.println("二年级的学生有:\n"+"nama\tID");
int x=2;
for(int i=0 ; i < n ; i++){
shool[i].locateprint(x);
}
}
class Student{
private String name;
private int ID;
private int state;
static int count;
Student(){
System.out.println("请输入第"+(++count)+"个学生的名字、ID、 年级");
Scanner sc = new Scanner(System.in);
name = sc.next();
ID = sc.nextInt();
state = sc.nextInt();
}
void locateprint(int i){
if(i == state)
System.out.println(name+"\t"+ID);
}
}