Classes and Objects


(来源:http://www.artima.com)

Objects and Java Seminar by Bill Venners
Lecture Handout

Agenda

  • Covers basics needed to write first app
  • Look at organization of the JVM
  • Talk about references, types, and arrays
  • Talk about variables, objects, and GC
  • Describe the parts of a class
  • Show a simple Java application

Where Data is Stored

  • The heap: all objects
  • Inside objects: instance variables
  • The stack: local variables
  • Method area: class (static) variables
  • Variables are of primitive or reference types

Object References

// Reference only
Account acct;

// Reference and object
LogFile log = new LogFile();

// Two ways to create strings
String s1 = new String("Hello, World!");
String s2 = "Hello, World!";

Primitive Types

  • Primitive types: byte, short, int, long, float, double, boolean, char
  • Ranges and behaviors independent of platform
  • Prefers portability over performance
  • Immutable wrapper types: Byte, Short, Integer, Long, Float, Double, Boolean, Character

Wrapper Classes

int i = 2001;
Integer i1 = new Integer(2001);
Integer i2 = i1;

Arrays

  • Arrays are full-fledged objects
  • JVM does bounds checking at run-time
  • Will be covered in detail in Lecture 3

Local Vars Go Out Of Scope

 1 {
 2     int i = 10;
 3     // Only i in scope here
 4     {
 5         int j = 20;
 6         // Both i and j in scope
 7         // Note: can't redefine i here
 8     }
 9     // i still in scope, j out of scope
10 }

Objects Become Unreferenced

 1 {
 2     Integer i = new Integer(10);
 3     {
 4         Character c = new Character('q');
 5     }
 6     // c out of scope
 7     // Character object unreferenced
 8 }
 9 // i out of scope
10 // Integer object unreferenced

A Class Defines a Type

  • The class keyword:
    class Account {
        // class definition goes here
    }
    
  • Can declare variables and create instances (objects):
    Account acct = new Account();
    
  • A class is made up of members: fields and methods

Fields

  • Fields are data variables:
    class Account {
    
        // balance: in American pennies
        private long balance;
    
        // the methods...
    }
    
  • Fields get default values
  • Each instance gets its own set of instance vars

Methods

  • Methods are functions:

     1 // In file classesandobjects/ex1/Account.java
     2 
     3 public class Account {
     4 
     5     // balance: in American pennies
     6     private long balance;
     7 
     8     // amount: in American pennies
     9     public boolean okToWithdraw(long amount) {
    10         return (amount <= balance);
    11     }
    12 
    13     // amount: in American pennies
    14     // return value: in American pennies
    15     public long withdraw(long amount)
    16         throws InsufficientFundsException {
    17 
    18         if (amount > balance) {
    19             throw new InsufficientFundsException(
    20                 amount - balance);
    21         }
    22 
    23         balance -= amount;
    24         return amount;
    25     }
    26 
    27     // amount: in American pennies
    28     public void deposit(long amount) {
    29 
    30         balance += amount;
    31     }
    32 }
    
  • Methods can only be defined inside classes
  • Example method call:
    Account acct = new Account();
    acct.deposit(15000L);
    long cash = acct.withdraw(4000L);
    

Parameters

  • List of primitive types and object references separated by commas
  • Variable name for each parameter
  • Everything (including object references) are passed by value:
    public int lastIndexOf(String str,
        int fromIndex) {
        //...
    }
    

Naming Conventions

  • Run words together, except for constants
  • Class names -- Capitalize first letter of each word: String, ArrayIndexOutOfBoundsException
  • Method names -- Captalize first letter of each word, except first: replace(), equalsIgnoreCase()
  • Constants -- Capitalize all letters; Separate individual words by underscores: MAX_VALUE, DECIMAL_DIGIT_NUMBER

Packages and Names

  • Classes partition names of fields and methods
  • Packages partition names of classes
  • Simple name: String
  • Fully qualified name: java.lang.String
  • Third party packages should begin with reverse domain name: com.artima.jvmsim.JVMSimulator
  • Some packages from Java API: java.lang, java.io, java.awt, java.util, java.applet

The Import Statement

  • Can use fully qualified names everywhere:
    java.util.HashMap h = new java.util.HashMap();
    
  • Can import a type, then use its simple name:
    import java.util.HashMap;
        //...
        HashMap h = new HashMap();
    
  • Can import all types with an asterisk:
    import java.util.*;
        //...
        HashMap h = new HashMap();
    
  • java.lang package imported automatically

Static Members

  • static keyword: "class variables" and "class methods"
  • Class variables: accessible to all instances and to class methods:
    class CoffeeCup {
        private static int cupCount;
        //...
    }
    
  • Class methods can be invoked without an instance:

    class CoffeeCup {
        private static int cupCount;
        public static int getCupCount() {
            return cupCount;
        }
        // ...
    }
    int count = CoffeeCup.getCupCount();
    

EchoArgs: A Java Application

 1 // In file classesandobjects/ex2/EchoArgs.java
 2 
 3 public class EchoArgs {
 4 
 5     public static void main(String[] args) {
 6 
 7         int argCount = args.length;
 8         for (int i = 0; i < argCount; ++i) {
 9 
10             if (i != 0) {
11                 System.out.print(' ');
12             }
13             System.out.print(args[i]);
14         }
15         System.out.println();
16     }
17 }

Exercises

Problem 1.

Test your setup: compile and run EchoArgs.java:
 1 // In file classesandobjects/ex2/EchoArgs.java
 2 
 3 public class EchoArgs {
 4 
 5     public static void main(String[] args) {
 6 
 7         int argCount = args.length;
 8         for (int i = 0; i < argCount; ++i) {
 9 
10             if (i != 0) {
11                 System.out.print(' ');
12             }
13             System.out.print(args[i]);
14         }
15         System.out.println();
16     }
17 }

Problem 2.

Create a Java application named Hello that prints out a greeting, such as the traditional, "Hello, world." Feel free to use the traditional greeting or come up with your own creative greeting.

Problem 3.

Change EchoArgs.java so that it changes all lower case letters to upper case before echoing them. For example, for the command line:
java UpperArgs Four sCore and seven years ago
this program would print:
FOUR SCORE AND SEVEN YEARS AGO

Problem 4.

Create a Java application named Counter that prints out the numbers between 1 and 100, inclusive. (i.e.: 1, 2, 3, ..., 99, 100)

Problem 5.

Change EchoArgs.java so that it prints out the arguments in reverse order, including the letters of the individual arguments. For example, for the command line:
java ReverseArgs one two three
this program would print:
eerht owt eno