内容发布更新时间 : 2025/5/9 3:16:38星期一 下面是文章的全部内容请认真阅读。
第3章习题解答
1.如何定义方法?在面向对象程序设计中方法有什么作用?
答:方法的定义包括方法名、方法形参、方法的返回值类型和方法体四部分,方法只能在类中定义。方法是对象的动态特征的描述,对象通过方法操作属性,进而改变对象的状态,完成程序所预期的功能。
2.定义一个Dog类,有名字、颜色、年龄等属性,定义构造方法用来初始化类的这些属性,定义方法输出Dog的信息。编写应用程序使用Dog。 答:
public class Dog{
private String name; private String color; private String age;
Dog(String n,String c,String a){ name = n; color = c; age = a; }
public String toString() {
return name + \,\,\ }
public static void main(String args[]) {
Dog dog = new Dog(\小白\白色\岁\ System.out.println(dog.toString()); } }
3.什么是访问控制修饰符?修饰符有哪些种类?它们各有何作用?
答:访问控制修饰符是对类、属性和方法的访问权限的一种限制,不同的修饰符决定了不同的访问权限。访问控制修饰符有3个:private、protected、public,另外还有一种默认访问权限。各个修饰符的作用如下表所示:
方法 类 public ic A cted B + C 认 B ate D B:包中的类 C:所有子类 D:本类 A:所有类
A:A:所所有有类类
4.阅读程序,写出程序的输出结果 class A{
private int privateVar; A(int _privateVar){ privateVar=_privateVar; }
boolean isEqualTo(A anotherA){
if(this.privateVar == anotherA.privateVar) return true; else
return false; } }
public class B{
public static void main(String args[]){ A a = new A(1); A b = new A(2);
System.out.println(a.isEqualTo(b)); } }
程序的输出结果为: false
5.阅读程序,写出程序的输出结果 public class Test {
public static void main(String[] args) { int x;
int a[] = { 0, 0, 0, 0, 0, 0 }; calculate(a, a[5]);
System.out.println(\ System.out.println(\ }
static int calculate(int x[], int y) { for (int i = 1; i < x.length; i++) if (y < x.length)
x[i] = x[i - 1] + 1; return x[0]; } }
程序的输出结果为:
the value of a[0] is 0 the value is a[5] is 5
6.阅读程序,写出程序的输出结果 public class Test {
public static void main(String[] args) {