目录
- 第6章习题
- 1.
- 2.类的2种可见性有什么区别?类成员的4种可见性有什么区别?
- 3.
- 4.
- 5.举例说明成员变量与局部变量的区别、类变量与实例变量的区别、类方法与实例方法的区别。
第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(instanceVariable); //类方法(静态方法)不能够访问实例变量(非静态字段)
System.out.println(classVariable); //类方法可以访问类变量
}
public static void main(String[] args) { //类方法
classMethod(); //类方法可以访问类方法
// instanceMethod(); //类方法(静态方法)不能够访问实例方法
}
}
- 编写一个满足下列要求的程序:
定义学生类类,属性分别是:姓名(name,String)、学号 (ID,int)和年级(state,int,1:新生,2:二年级,3:三年级,4:四年级)。
创建30个学生,学生的姓名、学号、年级通过键盘输入。
查找二年级的学生人数,并输出姓名和学号。
答:代码见Unit6 u6q6
//第六章第六题
private static void u6q6(){
int n=30; //创建30个学生
Student shool[] = new Student[n];
while(Student.count != n )
shool[Student.count] = new Student();
System.out.println("二年级的学生有:n"+"namatID");
int x=2;//二年级
for(int i=0 ; i < n ; i++){ //打印二年级学生的信息
shool[i].locateprint(x);
}
}
//第6题
class Student{
private String name;
private int ID;
private int state;//1:新生,2:二年级,3:三年级,4:四年级
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);
}
}