Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
62 views

CP1 Module 7 Object Data

1. The document discusses object-oriented programming concepts like modularity, classes, and objects in Java. 2. It explains that objects contain both data and methods, and that classes are descriptions that define what kind of data and methods an object will have. 3. As an example, it shows how to create a String object in Java by using the new operator and a constructor, and how to then call methods on that object by using a reference variable.

Uploaded by

sheilame nudalo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

CP1 Module 7 Object Data

1. The document discusses object-oriented programming concepts like modularity, classes, and objects in Java. 2. It explains that objects contain both data and methods, and that classes are descriptions that define what kind of data and methods an object will have. 3. As an example, it shows how to create a String object in Java by using the new operator and a constructor, and how to then call methods on that object by using a reference variable.

Uploaded by

sheilame nudalo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

SENIOR HIGH SCHOOL

First Semester S.Y. 2020-2021

MODULE 7
COMPUTER PROGRAMMING 1
(JAVA)

Name: _______________________________ Date :__________


Grade/Section: ________________________ Week : 7
Track/Strand: _________________________
Lesson 7 COMPUTER PROGRAMMING 1 (JAVA) – Object
Data

WHAT DO YOU EXPECT TO LEARN?

Content Standard:
The learners demonstrate understanding of the:
1. modularity;
2. classes and objects;
3. reference variables;
4. string objects; and
5. type wrappers and packages.

Performance Standard:
The learners should be able to:
1. create a program that uses objects defined in the standard
software packages that come with Java.
Objectives:
After the lesson, the learners should be able to:
1. define the concept of modularity, objects, and classes; and
2. plan for a concept for your own object and class.

PRELIMINARY ACTIVITY

Direction: Draw objects you can find around you. State the attributes (color,
weight, height, etc.) and give what data type you can use for each
attribute.
OBJECT DATA: Modularity and Objects

A vital idea in programming (and perhaps in all of science and math) is how
large things are built of smaller things, and how those large things are used to build
even larger things.

The classic example is Lego bricks, where individual bricks are used to build
larger assemblies which in turn are used to build even larger assemblies, which are
used to build even larger constructions.

In geometry, Euclid's axioms are the basic bricks, which are used to build basic
theorems, which in turn are used to build more theorems, which are used to build even
more advanced theorems. Over the years, a very large structure has been built out of
the fundamental axioms (and the building continues to this day).

In programming, this idea is called modularity. A module encapsulates some


well-defined functions and data and is used as a brick to build even larger modules. We
have already seen this with expressions built out of operands and operators, statements
built out of expressions, statements put into larger groups to make programs.

Industrial-strength programs can be very large. A modern operating system can


be 10s of millions of lines of code. This would be impossible to create without the idea
of dividing it into thousands of individual modules.

In object-oriented programming, the idea of modularity is implemented


with objects. An object contains both data and methods and can be used like a brick to
build larger objects.

OBJECTS AND PRIMITIVE DATA

A primitive data type uses a small amount of memory to represent a single item
of data. All data of the same primitive type are the same size.

For example, primitive


type int represents integers using 32 bits.
All variables of type int use 32 bits.

There are only eight primitive data types in


Java: byte, short, int, long, float, double, char, and boolean. A Java program
cannot define any other primitive data types.

An object is a large chunk of memory that can potentially contain a great deal of
data along with methods (little programs) to process that data.

There are thousands of object classes that come standard with Java, and a
programmer can easily create additional classes.
PICTURE OF AN OBJECT

An object consists of both data and methods.

The picture illustrates a conceptual object. The little yellow bricks represent bytes
of memory. The methods of the object and the data of the object are constructed out of
bytes. This object contains the characters
"Elementary, my dear Watson!" and contains several
methods to manipulate that data.

A class is a description of a kind of object.

A class is the data type of that kind of object.


A class describes what an object of a particular type
is made of, its data and its methods. A class is merely
a description. It is like a plan for building a
house. Before you build a house, you should have a
plan. Once you have a plan, however, you can build
any number of houses that follow that plan.

The picture represents an object of class String. Such an object contains a string


of characters and various methods that can do things with those characters.

CREATING AN OBJECT

The new operator asks for an object to be constructed. The Java virtual


computer creates an object by following the description contained in its class.

The example program creates a String object. When the program runs, the
expression

new String( "Elementary, my dear Watson!" )

creates a new String object by following the description contained in the String class.


This description is contained in a standard software package that comes with Java. The
particular object created in this case contains characters "Elementary, my dear Watson!".
The new object contains all the methods and features that are described in
the String class.

All objects of the same class contain the same methods. All objects of the same
class contain the same types of data although the values of the data will be different
from object to object. For example, all String objects contain the same methods.
All String objects contain a string of characters, but the characters will be different
from object to object.
The program could now use the methods of this object to do some things with
the characters. However, this program does nothing further. After the program stops
running, the object no longer exists. The memory out of which it was made can now be
used for other purposes.

Before the program runs, there is no object. The new String object is created as


the program runs.

The declaration

String str;

creates a reference variable, but does not create a String object. The variable str is


used to refer to a String after one has been created.

The next statement

str = new String( "Elementary, my dear Watson!" );

creates an object and puts a reference to that object in str.

After the program stops running, the String object no longer exists. Its memory
is reclaimed by the computer system for other uses.

OBJECT REFERENCE
Here is the assignment statement we are considering:

It works like this:

1. Evaluate the expression.

The expression

new String( "Elementary, my dear Watson!" )

is evaluated. This constructs (creates) a new object. The value of this expression is a
reference to the new object.

A constructor for an object has the same name as the class and is used with
the new operator. Sometimes (as in this example) a constructor requires parameters.
A constructor returns a reference to the object it has created. A reference to an
object describes its location in memory. It enables the Java virtual computer to find the
object.

2. Store the value in the variable.

In the second step, the reference (the value) is stored in the reference variable:

str = The reference to the string just created

Now whenever the program needs to refer to the object it uses the variable str.

A reference is like a cell phone number. Someone who has your number can send
you a message, and ask you to do something, no matter where you are. Think of your
boss calling you and sending a message, "Start working on that report!" This is like
using an object reference to ask the object to run a method.

Sometimes the variable str is called the "name" of the object. This is a


simplification and can lead to confusion if you are not careful. The object, the reference
variable, and the reference are three different things.

ANALOGY

Objects and references to objects are very common in the real world. But
sometimes the distinction between objects and object references is hard to see in a
program. Here is an analogy that may help:

object you

reference your cell phone number

a slip of paper with your cell phone number on it,


reference variable held by someone who wants to send messages to
you

Here is the statement we are considering:

And here are pictures of the action.


The picture on the left shows the program just as it starts to run. No objects have
been created yet, but the reference variable exists. The slash through the variable means
that it does not yet refer to an object. Then the assignment statement executes:

str = new String( "Elementary, my dear Watson!" );

This creates an object, fills it with data, and puts a reference to it in str.

The picture on the right shows the program after the assignment statement has
run. The reference is shown as an arrow that leads to the object, and this is a good way
to think of it.

The variable will continue to hold the reference to the object until some other
assignment statement changes it or the program ends.

RUNNING A METHOD
Here is the example program, now with additional statements:

The expression

str.length();

runs the length() method of the object referred to by str. This method counts the


number of characters in the data of the object. In our object, it counts the number of
characters in "Elementary, my dear Watson!" which is 27. That value is then assigned to
the int variable len. Space characters and punctuation characters are included in the
length of a string.
Calling a method means asking a method to run. This
program called the length() method. (Sometimes the phrase invoking a method is used
to mean the same thing.)

Methods frequently return a value. The length method returned the value 27.


(Sometimes a method is said to evaluate to a value.) It is as if the method call is
replaced by the value it returns. So that

len = str.length();
is replaced with

len = 27;

DOT NOTATION

The various things an object contains—its variables and its methods—are called
the members of that object. The members of an object are accessed using dot
notation, which looks like this:

objectReference.memberName

Usually the objectReference is contained in a variable, but not always. If you want


to run a method of the object, use the method name. If it needs parameters (values
supplied to the method), they go inside ( ) like this:

objectReference.methodName( parameter )

Always use ( ) with a method name, even if it needs no parameters.

DECLARING A REFERENCE VARIABLE

There are several ways to declare a reference variable:

ClassName variableName;

 This declares a reference variable and declares the class of the object it will later
refer to. No object is created.

ClassName variableName = new ClassName( parameter,


parameter, ... ) ;

 This declares a reference variable and declares the class of the object. But now, at
run time, a new object is constructed and a reference to that object is put in the
variable. Sometimes parameters are needed when the object is constructed.

ClassName variableNameOne, variableNameTwo ;

 This declares two reference variables, both potentially referring to objects of the


same class. No objects are created. You can do this with more than two variables,
if you want.
ClassName variableNameOne = new ClassName( parameter,
parameter, ... ),
variableNameTwo = new ClassName( parameter,
parameter, ... ) ;

 This declares two reference variables. At run time, two objects are created and
their references are assigned to the variables. Again, you can do this for more
than two as long as you follow the pattern.

OBJECTS CREATING OBJECTS

It seems a little odd that an object can create another object. This is not how real-
world objects usually behave. Bricks do not create other bricks. Cars do not create other
cars. But software objects often create new software objects.

Software objects are created:

1. By using a constructor.
2. By calling a method that constructs an object.

There is no difference between objects created one way or the other.

The substring() method of a String object creates a new object by asking the


Java virtual computer to create a new object. The virtual computer creates the new
object in the usual way by following the instructions contained in the class.

PACKAGES

A group of related classes is often put into a collection called a package.

Many packages come standard with Java. For example, the String class is part of
the package called java.lang. Several useful classes are part of that package. You can
use the classes in this package without doing anything special.

Other standard packages also come with Java. To use a class from one of these
packages your program must tell the compiler what package contains the class. One
way to do this is to use the package name with the class. Here is a program that
explicitly mentions where the String class is found:

This program works the same way as the previous version. The
package java.lang does not need to be explicitly mentioned when you need to
use String, although it does not hurt to do so.
import

Here is a program that creates a Scanner object. The program does nothing with this
object

The compiler is told that the class Scanner is in the package java.util. Another way


to do this is to import the class, as in the following program:

In the second version of the program, the statement:

import java.util.Scanner;

tells the compiler that the Scanner class is found in the java.util package, so the rest


of the program does not need to include the package name each time Scanner is used.

TYPE WRAPPERS

There is a division between primitive data and objects. The division sometimes


needs to be crossed.

F o r e a c h p r i m i t i

A w r a p p e r c l a s
up the data with an object, like
wrapping up a gift.

W r a p p e r c l a s s e s
can be converted into primitive
data. The table shows primitive types
and their wrapper classes. Java is case
sensitive, so byte and Byte are
different types.

A s a n e x a m p l e , t
primitive data type int. The same value
could be held in an object that is of type Integer. The object will use many more than
32 bits.

The wrapper classes are defined in the package java.lang and so (like all classes
in that package) are automatically available to your programs.

ASSESSMENT
Directions: Write each of these programs as specified. None of these programs ask the
user to enter data. Data are "hard coded" with declaration statements or
assignment statements.

Exercise 1 — Object Created at Run Time

Write a program that creates a String object that contains the string "Hello World"
(or some other favorite string). Assign the reference to the object to the reference
variable str. Write the characters of the object to the monitor:

System.out.println( str );

Run the program to confirm that it works as you expect. Now add a second reference
variable to the program, but don't create an object for it to refer to. Add a statement
that uses the second variable as if it held a valid object reference. Run the program,
and see what happens:

System.out.println( secondVariable );

Play around with this program for a while to cement the notion in you head that an
object and its reference variable are different things, and that an object is created at
run time.

Exercise 2 — String Length

Compile and run the StringDemo2 program from the chapter.

public class StringDemo2


{
public static void main ( String[] args )
{
String str;
int len;

str = new String( "Elementary, my dear Watson!" );

len = str.length();

System.out.println("The length is: " + len );

}
}
Now change the String in various ways and observe the effect on the computed
string length. Add extra spaces on either side and in the middle of the string; add
more punctuation; insert a tab character (a real tab character, not just spaces). Note
that the length of the string "MMMMMM" is the same as "iiiiii". The length is the
number of characters, not the actual length of line it takes to print them.

Exercise 3 — A  String Method that creates a new String


It is often useful to trim off extra spaces from both sides of a String.
The trim() method of String objects does that. It creates a new String object from
an existing one, where the new String object has all the characters of the original
except that spaces and tabs have been trimmed off the sides. The original String is
not changed. For example, after the following statements have executed

String first = new String(" In a Hole in the ground there lived a Hobbit. ")
String second;

second = first.trim();

there will be a second object, referred to by second, containing the characters

"In a Hole in the ground there lived a Hobbit."

Notice that internal extra spaces remain.

Write a program (or modify the previous one) that creates a String by calling
the trim() of an original String. Write both Strings to the monitor. Experiment
with spaces and tabs to determine exactly what is trimmed from the original.
FEEDBACK

________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

HOW DO YOU LIKE OUR TOPIC?

REFERENCES

1. http://programmedlessons.org/Java9/chap08/ch08_01.html
2. https://www.youtube.com/watch?v=qUXbJziVs_o
3. http://programmedlessons.org/Java9/chap09/ch09_01.html
4. https://www.youtube.com/watch?v=RA7wkTV6z4k

You might also like