JMU
Creating and Using Objects
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Key Concepts
Interchangeable Terms (Sometimes Also Modified by "Class" or "Instance")
Data Types in Java Revisited
Naming Conventions in Java Revisited
Instantiating Objects
Instantiating Objects (cont.)

An Example

javaexamples/basics/ObjectExample1.java (Fragment: 0)
        // Establish an identity for the object
        Color       jmuPurple;

        // Allocate memory for and initialize the attributes
        jmuPurple = new Color(69, 0, 132);
        
Instantiating Objects (cont.)
Using Objects
Using Objects (cont.)

An Example

javaexamples/basics/ObjectExample2.java (Fragment: 0)
        Color        lightRed, darkRed;
        int          blue, green, red, shades;

        // Initialize the attributes
        darkRed = new Color(102, 0, 0);

        // Use a getter/accessor
        blue = darkRed.getBlue();
        
        // Use another method
        lightRed = darkRed.brighter();
        
        // Use equals() and a static attribute of the Color class
        shades = 1;        
        if (!lightRed.equals(Color.RED))
        {
            shades++;
        }
        
Using Objects (cont.)
Using Objects (cont.)
Using Objects (cont.)

An Example

javaexamples/basics/NullExample1.java (Fragment: 0)
        // The variable darkRed has been declared as a Color
        // but not initialized

        // Print and use an Object which HAS NOT yet been initialized
        JMUConsole.println(darkRed.toString());
        JMUConsole.println(darkRed.brighter());        
        
Comparing Objects
Mutability
Mutability (cont.)
Using Different Objects/Classes in One Application

An Example

javaexamples/basics/ObjectExample3.java
import java.awt.*;

/**
 * A simple example that uses objects of different kinds
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ObjectExample3
{
    public static void main(String[] args)
    {
       Color        purple;       
       Frame        window;

        // Construct a Color object that is JMU purple
        purple = new Color(69, 0, 132);        

        // Construct a Frame object
        window = new Frame();

        // Set the title of the Frame
        window.setTitle("CS159");     

        // Set the size of the Frame
        window.setSize(200, 200);
        
        // Set the background color of the Frame
        window.setBackground(purple);        

        // Make the Frame visible
        window.setVisible(true);
        
    }

}