Another Simple Program 3

Another Simple Program 3 - Using and Creating Objects An...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
Using and Creating Objects An object is an entity in programs that you manipulate by calling methods. o Ex: System.out is an object that you manipulate by calling method println(): System.out.println("Hello World"); This method call results in the text message being printed in the console window. The identifier out is an object variable which is stored in the System class, and println is a method we can call on object out. We create our own objects in programs by using the new operator and a special method called a constructor. o Scanner scan; o scan = new Scanner(System.in); // new operator + invoking constructor (same name as class) In Java a variable name represents either a primitive value or an object. Reference variables, which represent objects, hold a reference (an address in memory) to objects (or the value null to indicate that no object is referenced).
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Unlike variables of a primitive type, references do not hold values directly. They hold pointers/memory addresses. Recall that Java does not have a built-in string type. Instead: String class in standard Java library. Declaring and Initializing Reference Variables The declaration of object variables looks similar to declarations of primitive variables: int num; String myName; But the first declaration creates a variable that holds an int value. The second declaration creates a String variable that hold the address in memory of a String. Above we created a String reference variable, but no String object is associated with it yet. We create a String object, or an instance of the String class, using the new operator, which returns the address of the new object.
Background image of page 2
num = 15; name = new String("Mary"); ^^^ Invoking, or calling, the constructor of the String class to set up the String object. A constructor is a special method that has the same name as the class. To construct an object, you:
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/24/2010 for the course CS 305j taught by Professor Mikescott during the Spring '10 term at University of Texas at Austin.

Page1 / 14

Another Simple Program 3 - Using and Creating Objects An...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online