chapter 6.3

Post on 02-Jul-2015

89 Views

Category:

Education

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CREATING OBJECTS FROM

PREDEFINED CLASS

Chapter 6.3:

Creating Objects

A variable holds either a primitive type or a

reference to an object

A class name can be used as a type to declare an

object reference variable

String name;

No object is created with this declaration

An object reference variable holds the address of

an object

The object itself must be created separately

Creating Objects

Generally, we use the new operator to create an

object

Creating an object is called instantiation

An object is an instance of a particular class

name = new String (“Ali bin Ahmad");

This calls the String constructor, which is

a special method that sets up the object

Constructing String objects

Strings stringRef = new String(stringLiteral);

eg.

String name = new String(“Muhammad Haziq”);

Since strings are used frequently, Java provides a

shorthand notation for creating a string:

String name = "Muhammad Haziq”;

Constructing String objects

New String objects are created whenever the String constructors are used:

String name4 = new String(); // Creates an object

String name5 = new String("Socrates");

String name6 = name4;

Invoking Methods

We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods

name.length()

A method may return a value, which can be used in an assignment or expression

count = name.length();

S.o.p(“Num. of char in “ + name+ “=“ + count);

A method invocation can be thought of as asking an object to perform a service

Object without object reference

cannot be accessed

String n1 = new String(“Ali“);

new String(“Abu“);

sv1: String: String

value = “Ali” value = “Abu”

n1n1- object reference variable

Object References

Primitive type variables ≠ object variables

References

Note that a primitive variable contains the value

itself, but an object variable contains the address

of the object

An object reference can be thought of as a pointer

to the location of the object

Rather than dealing with arbitrary addresses, we

often depict a reference graphically

"Steve Jobs"name1

num1 38

Assignment Revisited

The act of assignment takes a copy of a value and

stores it in a variable

For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Object Reference

Assignment For object references, assignment copies the

address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Austin"

name1

name2After:

"Steve Jobs"

Questions

String stud1 = new String(“Ani”);

int studID = 65000;

What does variable stud1 contains?

What does variable studID contains?

Is this allowed? stud1 = studID;

String stud1;

stud1 = new String(“Ani”);

stud1 = new String(“Obi”);

How many objects were created by the program?

How many reference variables does the program contain?

top related