CS 46A - Lecture 23

Cover page image

Pre-class reading

Static Variables

A Static Variable and Instance Variables

Static Variables

Lecture 23 Clicker Question 1

Harry tells you that he has found a great way to avoid those pesky objects and classes: Put all code into a single class and declare all methods and variables static. Then main can call the other static methods, and all of them can access the static variables. What do you think of Harry's plan?

  1. It won't work—you can't avoid using objects and classes
  2. It won't work—you can't call other static methods from main
  3. It will work, and it will make programs simpler to understand
  4. It will work, but it will make programs harder to understand


Scope of Local Variables

Scope of Local Variables

Overlapping Scope

Overlapping Scope

Lecture 23 Clicker Question 2

Consider the following program that uses two variables named r

public class RectangleTester 
   public static double area(Rectangle rect) 
      double r = rect.getWidth() * rect.getHeight(); 
      return r; 
   public static void main(String[] args) 
      Rectangle r = new Rectangle(5, 10, 20, 30); 
      double a = area(r); 


Organizing Related Classes into Packages

Syntax 8.2 Package Specification

Package Specification

Importing Packages

Package Names

Packages and Source Files

Lecture 23 Clicker Question 3

Which of the following are packages?

  1. The first three
  2. The last three
  3. The middle two
  4. All of them

Lecture 23 Clicker Question 4

Harry has found a great way of getting rid of all those pesky import statements. Instead of placing import java.util.Random at the top of the program, he simply writes java.util.Random instead of Random inside the program. What do you think?

  1. It won't work—you must use import statements to import packages other than java.lang
  2. It won't work—it's a syntax error to put the package name before a class.
  3. It works, and it makes programs simpler to read
  4. It works, but it makes programs harder to read