|
Creating and Using Objects
An Introduction with Examples in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
new operator (which is a unary operator that has a
constructor as its operand and evaluates to a reference)
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++;
}
null
(and is a reference/address that isn't valid)null
null will result in a run-time error
called a NullPointerException
== operator.equals() methodRectangle and Frame are
classes of mutable objects)String and Color are
both classes of immutable objects)
public attributes (but they are very dangerous
since there is no control over the changes that can be made)
set (and, hence, are often
called setters)
increaseBy())
Color class has a
darker() method that doesn't change the
owning object but returns another Color
object that is "darker")
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);
}
}
static Attributesstatic AttributesInteger Class:
MIN_VALUE
MAX_VALUE
Double Class:
NEGATIVE_INFINITY
POSITIVE_INFINITY
MIN_VALUE
MAX_VALUE
Math Class:
E (base of the natural log)PI
static Methodsstatic MethodsSystem Class:
currentTimeMillis()
exit()
Math Class (A Utility Class):
abs()
sin()
cos()
tan()
log()
pow()
sqrt()
static Methods (cont.)Integer Class:
parseInt()
toString()
Double Class:
parseDouble()
toString()
new Operator:
bullwinkle = Moose())