Vous êtes sur la page 1sur 16

Object-Oriented Programming

TOPIC TITLE: Objects and Classes

Specific Objectives:

At the end of the topic session, the students are expected to:

Cognitive:

1. Identify the difference between objects and classes.


2. Differentiate physical objects from conceptual objects.
3. Create a class.
4. Identify the different types of access modifiers.
5. Explain what methods are and how they are declared and used
in Java.
6. Use constructors to create objects.
7. Explain how to use method overloading and overloaded
constructors.
8. Recognize the use of the dot notation.
9. Use the this keyword.
10. Import Java packages.

Affective:

1. Listen to others with respect.


2. Participate in class discussions actively.

Psychomotor:

1. Declare a class in a program.


2. Declare variables in a program.
3. Use methods in creating a Java program.
4. Use method overloading.
5. Use constructors to create objects.
6. Apply accessor and mutator methods.

MATERIALS/EQUIPMENT:

o topic slides
o OHP

TOPIC PREPARATION:

o Have the students research on the following:


Declaring classes and objects
Access modifiers
Declaring methods and constructors
Method overloading
this keyword
Importing packages
Type casting
o Prepare additional examples on the topic presented.
o It is imperative for the instructor to incorporate various kinds of
teaching strategies while discussing the suggested topics. The
instructor may use the suggested learning activities below to
facilitate a thorough and creative discussion of the topic.
o Prepare the slides to be presented in class.

Objects and Classes


Page 1 of 16
Object-Oriented Programming

TOPIC PRESENTATION:

The topic will introduce the students on how to write classes, declare
member variables, methods, and constructors.

This will be the suggested flow of discussion for the course topic:

1. Ask the students the question: “What makes an object?”


2. Ask the students to define what objects and classes are as
discussed in their previous lesson.
3. Discuss the classification of objects: physical and conceptual.
The discussion will be based on the examples presented in the
slides.
4. Illustrate the relationship between an object and a class in the
slide.
5. Discuss the syntax for declaring a class and its example.
6. Explain the four access modifiers in Java.
7. Discuss how member variables are declared.
8. Discuss the syntax for declaring methods.
9. Identify the conventions in naming methods.
10. Discuss how to return a value from a method.
11. Discuss the syntax for declaring constructors and its examples.
12. Explain the concept of method overloading and overloading
constructors.
13. Explain how to use the this keyword in Java.
14. Discuss how to import packages in Java.
15. Discuss what type casting is and identify its two types.
16. After discussing the whole topic, let the students answer the
exercises provided in the slides. Discuss the answers in the
class.

Objects and Classes Objects and Classes


Pages 1-4 of 40
Most people define an object as something initially perceive by human
senses. Objects can be classified into two:

Physical – objects which can be seen or touched (e.g. students,


room, buildings, etc.)
Conceptual – objects which can’t be touched but they exists
(e.g. department, enrollment, etc.)

Each of these objects has their own attributes (variables) and


behaviors/abilities (methods).

As discussed in the previous lesson, objects in object-oriented


programming are representations of objects in the real world. Its main
purpose is to allow programmers to bundle or group together
attributes/data/state/variables and functions/behaviors/methods into a
single logical unit.

Let us consider again the object Student. There are many possible
attributes that a Student can have like Name, ID number, Birthday,
Address, and GPA. All of these are data that pertain to a single student.

Another example would be the object Course. This object can have
attributes like Course Number, Course Name, Prerequisites, and
Credits. These attributes can characterize a Course object.

NOTE: Provide examples for both physical and conceptual objects then
let the students enumerate its possible attributes. You may write their

Objects and Classes


Page 2 of 16
Object-Oriented Programming

answers on the board and discuss them to the class.

Now let us consider the methods or behaviors that an object has. Think
of methods as activities or abilities that a certain object can perform. For
example, a Student may enroll in a course or may drop a certain course.
These are some examples of activities that the Student object may
perform.

The Course object also has its own methods. The Course object is
responsible if a student can register or determine if the student has met
the prerequisite prior to taking another subject.

NOTE: Provide another object example on class and let the students
define its own methods. You may use the Car and Department or
maybe animals (e.g., dog or bird) as examples.

As discussed in the previous lesson, classes are templates of objects.


They define what characteristics and behavior a certain object has.

The difference between a class and an object is that a class is the


template of an object while objects are the actuality of a certain class.

The illustration shows the relationship between an object and a class


(refer to the slide). Recall that we defined a class as a template of an
object. In this case, the class is a generic entity while the object is
specific. For example, we can think of Juan dela Cruz as an object of
class Person, specifically “Juan dela Cruz is an instance of Person.”
Hence, Juan dela Cruz possesses the characteristics and behaviors
defined in a Person.

Relationship between an object and a class

Another way of reading “is an instance of” might be “is an example of”.
We can then say “Juan dela Cruz is an example of a Person.

[Note that this relationship can also be read as “Juan dela Cruz IS A
person.” This, however, is not used since the “is-a” relationship is used
in object-oriented programming to show the relationship between a
superclass and its subclass/es.]

[Objects and Classes, Pages 1-4 of 40]

Objects and Classes Page 3 of 16


Object-Oriented Programming

Declaring a Class Declaring a Class


Pages 5-6 of 40
Classes are the basic building blocks of object-oriented Java programs.
The syntax for declaring a class is:

<modifier> class ClassName {


//field, constructor, and method declarations
}

Generally, declaring a class can include the following components, in


order:

1. Modifiers such as public or private.


2. The keyword class used to create a class in Java.
3. The class name, with initial letter capitalized by convention.
Think of an appropriate name for your class. Don’t just call your
class ABC or any random names you can think of. Be
descriptive.
4. The class body surrounded by braces {}.

An example would be a class named Horse.

public class Horse


{
//Horse’s variables and methods here…
}

[Declaring a Class, Pages 5-6of 40]

Declaring Member Variables Declaring Member Variables


Pages 7-10 of 40
There are several kinds of variables and these are the following:

Fields – member variables of a class


Local Variables – variables declared in a method or block of
code
Parameters – variables used in method declarations

Field declarations are composed of three components:

1. Zero or more modifier, such as public or private


2. The field’s (data) type
3. The field’s name

<modifier> <type> <name> [= <default value>];

A public modifier means that the variables are accessible from


all classes.
A private modifier means that the variables are only
accessible within the class. Other objects cannot access these
variables directly.
The field’s (data) type can be primitive types, such as int,
float, boolean, etc. You can also use reference types, such
as strings, arrays, or objects.

Objects and Classes Page 4 of 16


Object-Oriented Programming

For example, consider the program segment below:

public class StudentRec


{
public String name;
public String address;
public int age;
public double average;

//more code here…


}

This declares a class named StudentRec. The class access modifier


is public. It has four fields: name, address, age, and average. The
name and address are Strings while age is an integer and average
is double.

Another example is shown below:

public class Bicycle {

private int cadence;


private int gear;
private int speed;

//core here…
}

The private here means that the variables are only accessible within
the class. Other objects cannot access these variables directly.

Consider the following coding guidelines when declaring member


variables:

Declare all instance variables on the top of the class declaration.


Declare one variable for each line.
Instance variables should start with small letter.
Use an appropriate data type for each declared variable.
Declare instance variables as private so that only class methods
can access them directly.

You can also declare a variable static by using the static keyword.
For example,

public class StudentRec


{
private static int studCount;

//more code here…


}

[Declaring Member Variables, Pages 7-10 of 40]

Page 5 of 16
Objects and Classes
Object-Oriented Programming

Access Modifiers Access Modifiers


Pages 11-13 of 40
Access modifiers help you set the level of access you want for classes
as well as the fields, methods, and constructors in your classes. There
are three specified and one default level of access.

Public – specifies that class members are accessible to anyone, both


inside and outside the class. Any object that interacts with the class can
have access to the public members of the class. In other words, public
access may be accessed from anywhere by anyone. For example,

public class StudentRec {


//default access to instance variable
public int name;

//default access to method


public String getName() {
return name;
}
}

Private – specifies that the class members are only accessible by the
class they are defined in. For example,

public class StudentRec {


//default access to instance variable
private int name;

//default access to method


private String getName() {
return name;
}
}

Protected – specifies that the class members are accessible only to


methods in that class and the subclasses of the class. For example,

public class StudentRec {


//default access to instance variable
protected int name;

//default access to method


protected String getName() {
return name;
}
}

Default – specifies that only classes in the same package can have
access to the class’ variables and methods. There is no actual keyword
for the default modifier. It is applied in the absence of an access
modifier. For example,

public class StudentRec {


//default access to instance variable
int name;

//default access to method


String getName() {
return name;
}
}

Objects and Classes Page 6 of 16


Object-Oriented Programming

[Access Modifiers, Pages 11-13 of 40]

Declaring Methods Declaring Methods


Pages 14-17 of 40
As defined in the previous lesson, a method is a self-contained block of
program code that is similar to a procedure. It is a sequence of
instructions that a class or an object follows to perform a task. To
execute a method, you invoke or call it from another method; the calling
method makes a method call, which invokes the called method. Any
class can contain an unlimited number of methods, and each method
can be called an unlimited number of times.

To declare methods, we follow the syntax as:

<modifier> <returnType> <name> (<parameter>*) {


<statement>*
}

Generally, method declarations have the following components:

1. Modifier – this includes public or private


2. Return type – the data type of the value returned by the method,
or void if the method does not return a value
3. Method name – can be any valid identifier
4. Parameter list in parenthesis – a comma-delimited list of input
parameters, preceded by their data types, enclosed by
parentheses, (); if there are no parameters, you must use empty
parentheses
5. Method body – enclosed between braces, the method’s code,
including the declaration of local variables goes here

There are also conventions in naming methods. Method names should


be a verb in lowercase or a multi-word name that begins with a verb in
lowercase, followed by adjectives, noun, etc. In multi-word names, the
first letter of each of the second and following words should be
capitalized. For example,

run
runFast
getBackground
getAverage
compareTo
setX
isEmpty

Objects and Classes Page 7 of 16


Object-Oriented Programming

Consider the example below:

public class Sample {


public int num;

public int compute(int x, int y)
{
//your statements here…
}
}

[Declaring Methods, Pages 14-17 of 40]

Methods that Return Values Methods that Return Values


Page 18 of 40
The return type for a method can be any type used in Java, which
includes the primitive types like int, double, char, etc., as well as
class types.

A method’s return type is declared in its method declaration. Within the


body of the method, the return statement is used to return the value.

A method can be declared void that doesn’t return a value. If you try
to return a value from a method that is declared void, a compiler error
will be generated.

Any method that is not declared void must contain a return statement
with a corresponding return value:

return returnValue;

Take note that the data type of the return value must match the
method’s declared return type. For example, you cannot return an
integer value from a method declared to return a Boolean.

[Methods that Return Values, Page 18 of 40]

Accessor Methods Accessor Methods


Pages 19-21 of 40
An accessor is a method that is used to read values from member fields
(instance/static). It returns the value of the field. An accessor method is
usually written as:

get<NameOfField>

Consider the example below:

public class StudentRecord {


public String name;

public String getName()
{
return name;
}
}

Objects and Classes


Page 8 of 16
Object-Oriented Programming

In the given example, public modifier means that the method can be
called from objects outside the class. The return type of the method is
declared String, which means that the method should return a value of
type String. The name of the method is getName.

Another example is illustrated below:

public class StudentRecord {


public String name;

public double getAverage()
{
double result = 0;
result = (mathgrade + sciencegrade +
englishgrade)/3;
return result;
}
}

[Accessor Methods, Pages 19-21 of 40]

Mutator Methods Mutator Methods


Pages 22-23 of 40
A mutator is a method that is used to write or change the value of
member fields (instance/static). It is usually written as:

set<NameOfField>

For example,

public class StudentRecord {


public String name;

public void setName(String temp)
{
name = temp;
}
}

The method is declared public which means that it can be called from
objects outside the class. void means that the method does not return
any value. setName is the name of the method. String temp is the
parameter that will be used inside the method.

Objects and Classes Page 9 of 16


Object-Oriented Programming

As mentioned earlier, void means that the method does not return any
value. Typically, mutators do not return any value although some
programmers prefer to return the new value of the field for checking
purposes (i.e., method returns a specified value when an error/exception
occurs).

[Mutator Methods, Pages 22-23 of 40]

Static Methods Static Methods


Page 24 of 40
Below is an example that illustrates a static method.

public class StudentRec


{
private static int studCount;
public static int getStudCount()
{
return studCount;
}

//more code here…


}

The modifier is declared public which means that the method can be
called from objects outside the class. The method is static and
should be called by typing, [ClassName].[methodName]. For example,
in this case, we call the method StudentRec.getStudCount(). The
return type of the method is int, which means that the method should
return an integer value. getStudCount is the name of the method.

[Static Methods, Page 24 of 40]

Method Overloading Method Overloading


Pages 25-26 of 40
A method has a unique name within its class. On the other hand, a
method might have the same name as other methods due to method
overloading.

Overloading refers to the definition of multiple methods with the same


name, but with different arguments or parameter list. Since method
names typically represent an action, this allows you to define how to
perform the same action on different types of inputs. The program
selects which version of a method to invoke based on the parameters
provided. Hence, you can define methods with the same number of
parameters as long as the sequences of parameter types are different.

Here is an example:

class Data
{
public int add(int x) {
return x + 5;

Objects and Classes


Page 10 of 16
Object-Oriented Programming

public int add(int x, int y)


{
return x + y;
}
public int add(int x, int y, int z)
{
return x + y + z;
}
}

Notice that there are several methods having the same name add().
Even though the names of the methods are the same, the methods can
be distinguished by the number of parameters each method takes.

Here is another example illustrating method overloading:

public void print(String temp) {


System.out.println(“Name:” + name);
System.out.println(“Address:” + address);
System.out.println(“Age:” + age);
}
public void print(double mGrade, double sGrade,
double eGrade) {
System.out.println(“Name:” + name);
System.out.println(“Math Grade:” + mGrade);
System.out.println(“Science Grade:” + sGrade);
System.out.println(“English Grade:” + eGrade);
}

[Method Overloading, Pages 25-26 of 40]

Constructors Constructors
Pages 27-32 of 40
A constructor is a special type of method that establishes or creates a
new object. In Java, constructors have the same name as their class
and have no return value in their declaration.

A constructor cannot be called directly. It is called when using the new


operator during class instantiation.

To declare a constructor, the syntax is:

<modifier> <className> (<parameter>*) {


<statement>*
}

Objects and Classes


Page 11 of 16
Object-Oriented Programming

For example,

public Bicycle(int startSpeed, int startGear)


{
speed = startSpeed;
gear = startGear;
}

A default constructor is one that requires no arguments or parameters.


It is created automatically by the Java compiler for any class you create
whenever you do not write your own constructor.

For example,

public StudentRecord()
{
//insert code here…
}

In layman’s term, the role of a constructor is to give birth or give life to


the object of that class. Without the constructor, an object of a class
would not be able to use its attributes and methods not unless they are
said to be static.

The new keyword is the key to instantiating an object. For instance,


assume that a class Person exists. An object cannot exist without a
reference to it. So the reference must be declared before the object can
be created. The reference may be declared separately or in one line.

Person pedro;
pedro = new Person( );

In this example, the first line just declares a variable pedro that is of
type Person. The second line uses the new operator to invoke the class
constructor Person()to create the object and assign this to the variable
pedro. Every class must have at least one constructor to instantiate it.
If you don’t declare any constructors in your class, the compiler will
automatically declare one with no arguments.

Objects and Classes Page 12 of 16


Object-Oriented Programming

Another example would be:

class Person {
String name;
//Constructor
public Person() {
name = “pedro”;
}
int getName(){
return name;
}
}

class SamplePerson {
public static void main(String[] args)
{
//Instantiation
Person x;
x = new Person();
System.out.print(“\nHello ” +
x.getName());
}
}

Now, here is an example illustrating an overloaded constructor:

public StudentRec()
{
//code here…
}
public StudentRec(String Temp)
{
this.name = temp;
}
public StudentRec(String name, String address)
{
this.name = name;
this.address = address;
}
public StudentRec(double mGrade, double sGrade,
double eGrade)
{
mathGrade = mGrade;
scienceGrade = sGrade;
englishGrade = eGrade;
}

[Constructors, Pages 27-32 of 40]

Objects and Classes Page 13 of 16


Object-Oriented Programming

Dot Notation Dot Notation


Page 33 of 40
If you want to read a value from an instance variable, you have to
specify the object you want to get it from. This is done in Java using the
“dot notation.”

Here is an example that illustrates the dot notation:

int x = blank.x;

The expression blank.x means "go to the object blank refers to, and
get the value of x." In this case we assign that value to a local variable
named x. The purpose of the dot notation is to identify which variable
you are referring to unambiguously.

System.out.println (blank.x + ", " + blank.y);


int distance = blank.x * blank.x + blank.y * blank.y;

[Dot Notation, Page 33 of 40]

The this Keyword The this Keyword


Pages 34-36 of 40
this (or self) is a keyword in Java that can be used in instance methods
(or a constructor) to refer to the object on which the currently executing
method has been invoked. The this keyword is commonly when a field
is shadowed or obscured by a method or constructor parameter.

To use the this keyword, we simply write:

this.<nameOfTheField>

To illustrate how the this keyword is used, consider the example


below:

public class Point {


public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

The this keyword indicates that the value of the method parameters x
and y will be assigned to the fields x and y, respectively. Without the
this keyword, the use of variables x and y as method parameters
preclude access to the fields x and y.

Objects and Classes Page 14 of 16


Object-Oriented Programming

Another example would be:

public int getEmpNum()


{
return empNum;
}

public int getEmpNum()


{
return this.empNum;
}

The two getEmpNum() methods perform identically. The first method


simply uses the this keyword without you being aware of it. The
second method used the this keyword explicitly. There is really no
need for the this keyword in this case since empNum can only refer to
the field in this case.

[The this Keyword, Pages 34-36 of 40]

Packages Packages
Pages 37-38 of 40
A package is a named collection of classes. It is Java’s means of
grouping related classes and interfaces together in a single unit.
(Interfaces will be discussed further in the succeeding sessions)

To be able to use classes outside of the package you are currently


working in, you need to import the package of those classes.

By default, all Java programs import the java.lang.* package. This


package contains classes that give Java much of its power. It is
automatically used by every Java program. That is why you can use
classes like String and Integers inside a program even though you have
not defined these classes nor imported any packages. Other set of
packages include the following:

java.io – responsible for the input and output operations of the


Java language
java.util – features classes that encapsulate useful data
structures, including stacks, vectors, dates, dictionaries, hash
tables and bit fields
java.net – features classes that handles online communications
java.applet – responsible for the creation of Java applets
java.awt – provides classes needed to run Java programs in a
windowed environment

The syntax for importing packages is:

import <nameOfPackage>;

For example,

import java.awt.*;
import java.io;

[Packages, Pages 37-38 of 40]

Objects and Classes


Page 15 of 16
Object-Oriented Programming

Exercises Exercises
Pages 39-40 of 40
Ask the students to perform the following exercises and then discuss the
answers in the class.

1. Consider the program segment below.

public class Exercise1 {


public static int x = 7;
public int y = 3;
}

What are the class variables? What are the instance variables?

2. Determine the error in the program segment below.

public class Exercise2 {


public static void main(String[] args) {
Rectangle myRect;
myRect.width = 40;
myRect.height = 50;
System.out.println("Rectangle’s area is " +
myRect.area());
}
}

[Exercises, Pages 39-40 of 40]

EVALUATION/GENERALIZATION:

o A method may or may not return a value. One that does not
return a value is called a void method.
o A constructor is a special method that is executed when a new
object is created. Its purpose is to initialize the object into a
valid state.
o A public method that retrieves a property of an object is called
an accessor.
o A public method that changes a property of an object is called a
mutator.
o Methods with the same name are called overloaded methods.
o Ask the students to perform the exercises provided in the slide
and the laboratory exercise.

REFERENCES:

Wu, C. Thomas, (2004), An introduction to object-oriented


programming with java (3rd ed.), McGraw Hill
rd
Farrell, Joyce, (2006), Java programming (3 ed.), Thomson Course
Technology
Retrieved, September 11, 2007, www.wikipedia.org
Retrieved, September 11, 2007, www.java.sun.com and
www.java.about.com
Retrieved, September 14, 2007, http://www.beginner-java-
tutorial.com/java-access-modifiers.html

Page 16 of 16
Objects and Classes

Vous aimerez peut-être aussi