Documentation

The Java™ Tutorials
Hide TOC
Questions and Exercises问题和练习
Trail: Learning the Java Language
Lesson: Classes and Objects

Questions and Exercises: Objects问题和练习:对象

Questions问题

  1. What's wrong with the following program?以下程序有什么问题?

    public class SomethingIsWrong {
        public static void main(String[] args) {
            Rectangle myRect;
            myRect.width = 40;
            myRect.height = 50;
            System.out.println("myRect's area is " + myRect.area());
        }
    }
  2. The following code creates one array and one string object.下面的代码创建一个数组和一个字符串对象。How many references to those objects exist after the code executes?代码执行后,存在多少对这些对象的引用?Is either object eligible for garbage collection?这两个对象都有资格进行垃圾收集吗?

    ...
    String[] students = new String[10];
    String studentName = "Peter Parker";
    students[0] = studentName;
    studentName = null;
    ...
  3. How does a program destroy an object that it creates?程序如何销毁它创建的对象?

Exercises练习

  1. Fix the program called SomethingIsWrong shown in Question 1.修复问题1中显示的名为SomethingIsWrong的程序。

  2. Given the following class, called NumberHolder, write some code that creates an instance of the class, initializes its two member variables, and then displays the value of each member variable.给定以下名为NumberHolder的类,编写一些代码来创建该类的实例,初始化其两个成员变量,然后显示每个成员变量的值。

    public class NumberHolder {
        public int anInt;
        public float aFloat;
    }

Check your answers.检查你的答案。


Previous page: Questions and Exercises: Classes
Next page: Nested Classes