0% found this document useful (0 votes)
46 views34 pages

Session03-Classes and Objects

This document provides an overview of classes and objects in Java. It discusses key concepts like object-oriented programming, classes, objects, encapsulation, and inheritance. It explains how to define classes with member variables, methods, and constructors. It also covers creating objects from classes, accessing object fields and methods, and overloading constructors. The document uses examples like vehicles, employees, and arrays to demonstrate working with classes and objects.

Uploaded by

tuan nguyen anh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views34 pages

Session03-Classes and Objects

This document provides an overview of classes and objects in Java. It discusses key concepts like object-oriented programming, classes, objects, encapsulation, and inheritance. It explains how to define classes with member variables, methods, and constructors. It also covers creating objects from classes, accessing object fields and methods, and overloading constructors. The document uses examples like vehicles, employees, and arrays to demonstrate working with classes and objects.

Uploaded by

tuan nguyen anh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Session 03

Classes and Objects

(http://docs.oracle.com/javase/tutorial/java/javaOO/index.html)

Session 03 - Classes and Objects


Objectives
• Object-Oriented Programming Concepts.
• Information about defining your own classes,
including declaring member variables,
methods, and constructors.
• Learn to use your classes to create objects,
and how to use the objects you create.

Session 03 - Classes and Objects


Introduction to Object-Oriented Programming
• An object-oriented program
is made of objects. Each
object has a specific
functionality, exposed to its
users, and a hidden
implementation.
• Many objects in your
programs will be taken from
a Java library; others will be
custom designed.
• Traditional structured programming consists of designing a set of
procedures (or algorithms) to solve a problem.
Algorithms + Data Structures = Programs (Prentice Hall, 1975)
• For small problems, the breakdown into procedures works very well.
• But objects are more appropriate for larger problems.
Session 02 - Learning the Java
Language 
Introduction to Object-Oriented Programming
• Consider a simple web browser.
• It might require 2,000
procedures for its
implementation, all of which
manipulate a set of global data.
• In the object-oriented style,
there might be 100 classes with
an average of 20 methods per
class
• It is far easier to search for the
culprit among the 20 methods
that had access to that data
item than among 2,000
procedures.

Session 02 - Learning the Java


Language 
Object-Oriented Programming Languages
• Everything is an object.
• A program is a bunch of objects telling each other what to do, by
sending messages.
• Each object has its own memory, and is made up of other objects.
• Every object has a type (class).
• All objects of the same type can receive the same messages.
• Key object-oriented programming concepts
– Objects and Classes
– Methods and Variables
– Encapsulation
– Inheritance
– Polymorphism
What is an Object?
• Object is an entity and is the key to
understanding object-oriented technology in
OOP programming.
• In OOP, software objects are often used to
model the real-world objects that you find in
everyday life.
• Examples of real-world objects are student, animal,
bank account, worker, your bicycle, or your car.

Session 02 - Learning the Java


Language 
Software object
• From a programming point of view, Software object explains how state
and behavior are represented within an object.
• Real-world objects share two characteristics as state and behavior.
• Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail).
• Software object is a data structure, a variable. It has a memory location
allocated in a program. An object stores its state in data fields and exposes
its behavior through methods.

Session 02 - Learning the Java


Language 
Benefits of bundling code in software object
• Software
objects
provides a
number of
benefits:
• Modularit
y
• Informatio
n-hiding
• Code re-
use
What is a Class?
• A class is the template or blueprint from which objects are made
• Object myBicycle is an instance of the class Bicycle.
• In Java programming, Encapsulation (sometimes called information hiding)
is a key concept in working with objects.
• Encapsulation is simply combining data field and behavior in one class and
hiding the implementation details with the access modifier private from
the users of the object.
• Class Car for creating object redCar, yellowCar
• Class Animal for creating object lion, dog

Session 02 - Learning the Java


Language 
Identifying Classes
• A simple rule of thumb in identifying classes is to look for nouns in
the problem analysis.
• Methods, on the other hand, correspond to verbs.
• For example, in an Pizza order-processing system, some of the nouns
are
• Customer • Order • OrderDetails
• Next, look for verbs. Customer need to register(), login(), add(),
edit(), remove(), view(), search()
• With each verb, identify the object that has the major
responsibility for carrying it out. Only experience can help you
decide which nouns and verbs

Session 02 - Learning the Java


Language 
Identifying Classes
• An UML Class Diagram

Attribute, Field

Action, Behaviour

4 class types:
- Entity class
- Library class
- Controller class
- Boundary class
Session 02 - Learning the Java
Language 
Declaring Classes
• Syntax to define a class
[public] class MyClass [extends MySuperClass implements
YourInterface]{
//field declarations
//method definitions
}

• The class body contains:


 State of the class and its objects.
 Methods to implement the behavior of the class and its objects.
• Basic methods of entity classes:
 constructors
 getters and setters
 toString.
• Constructors for initializing new objects.
Session 03 - Classes and Objects
Declaring Member Variables
• Three kinds of variables:
– Member variables in a class— fields.
– Variables in a method or block of code
— local variables.
– Variables in method declarations—
parameters.
Declaring Classes
• Class declarations can include these
components, in order:
• Access Modifiers of class:
• public and default
– Access Modifiers of components:
• public, private, protected,
default

• The class name, with the initial letter capitalized


• The name of the class's parent (superclass), if any, preceded by the
keyword extends.
• A class can only extend (subclass) one parent.
• A comma-separated list of interfaces implemented by the class
class Bicycle extends Vehicle implements A, B, C { … }
Session 03 - Classes and Objects
First Steps with Constructors
• Constructors that are invoked to create
objects from the class blueprint.
• This constructor runs when you
construct new objects of the class
• Constructor declarations look like
method declarations—except that they
use the name of the class and have no
return type.
• A constructor can only be called in
conjunction with the new operator
• The compiler automatically provides a
no-argument, default constructor for
any class without constructors.
• The default constructor assigns all the
object variables to empty values:
number=0, logical=false, char='\0',
reference=null. Session 03 - Classes and Objects
Overloading Constructors
• Sometimes there is a need of
initializing an object in different
ways. This can be done using
constructor overloading
• If we don’t define any
constructor, the compiler creates
the default constructor (also
known as no-arg constructor)
during compilation

Session 03 - Classes and Objects


The accessor and mutator methods
• Sometimes, it happens that
you want to get and set the
value of an instance field.
Then you need to supply three
items:

• A private data field

• A public field accessor


method (getter)

• public field mutator


method (setter)
Creating and using Objects
• Class provides the blueprint for
objects; you create an object from
• Refer an object's Fields
a class. objectReference.fieldName
• Statement has three parts: String fullname = new
– Declaration: are all variable Employee().getFullname();
declarations that associate a System.out.println(“Fullname:"+
variable name with an object e.getFullname());
type.
Employee e; • Calling an object's Methods
– Instantiation: The new keyword objectReference.methodName(
is a Java operator that creates
the object. argumentList);
– Initialization: The new operator or: objectReference.methodName();
is followed by a call to a System.out.println(“Salary of
constructor, which initializes the employee: " + e.salary());
new object.
e = new Employee(); Session 03 - Classes and Objects
Object Array Sample
Encapsulation
When classes are defined, programmers can
specify that
certain methods or state variables remain hidden

inside
These the and methods are
variables Visible Methods
accessible from within the class,
class. Hidden
but not accessible outside it. State
Variables
 The combination of collecting all
and
Methods
the attributes of an object into a
single class definition, combined
Visible Variables
with the ability to hide some
definitions and type information
within the class, is known as
encapsulation.
Encapsulation
Instance balance()
variables

withdraw() theBalance deposit()


acctNumber

Methods
accountNumber()

State variables make up the nucleus of the object.


Methods surround and hide (encapsulate) the
state variables from the rest of the program.
Encapsulation Example

22 of 30
Encapsulation: Access Modifiers
• The first (left-most) modifier used lets you
control what other classes have access to a
member field.
– public modifier—the field is accessible from all
classes.
– private modifier—the field is accessible only within
its own class.

Session 03 - Classes and Objects


Inheritance
• Object-oriented
programming allows
classes
to inherit commonly
used state and behavior
from other classes.
• Bicycle now becomes
the superclass of
subclasses
MountainBike, RoadBike,
and TandemBike

Session 02 - Learning the Java


Language 
Implements Interface

• An interface is a group of related methods


with empty bodies.

Session 02 - Learning the Java


Language 
Defining Methods
• Methods belong to a class
• Defined inside the class
• Heading
• Return type (e.g. int, float, void)
• Method Name (e.g. max)
• Parameters (e.g. int numOfStudent)
• The 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.
• Body
• enclosed in braces {}. Declarations and/or statements.
• Overloading Methods:
• Methods within a class can have the same name if they have different
parameter lists. Session 03 - Classes and Objects
Defining Methods Sample

Session 03 - Classes and Objects


Defining Methods (Overloading)
• A Sample of Overloading methods
• Overloaded methods are
differentiated by the number
and the type of the arguments
passed into the method.
• In the code sample, draw(String
s) and draw(int i) are distinct
and unique methods because
they require different argument
types

Session 03 - Classes and Objects


Passing Information to a Method or a Constructor
• Parameter Types Primitive arguments are passed by
– You can pass an argument of value.
any data type into a method
or a constructor. This includes
primitive data types, such as
doubles, floats, and integers,
and reference data types,
such as classes and arrays
• Arguments are passed by value
• Primitive arguments are passed
by value.
• Reference data type parameters
are also passed by value.

Session 03 - Classes and Objects


Passing reference data Example
Reference data type parameters are
also passed by value.
Passing reference data Example

Session 03 - Classes and Objects


Garbage Collection

• Most modern languages permit you to allocate data


storage during a program run. In Java, this is done
directly when you create an object with the new
operation and indirectly when you call a method that
has local variables or arguments.
• Method locals and arguments are allocated space on
the stack and are discarded when the method exits,
but objects are allocated space on the heap and have
a longer lifetime.

Session 03 - Classes and Objects


Garbage Collection

• In Java, you never explicitly free memory that you


have allocated; instead, Java provides automatic
garbage collection.
• The runtime system keeps track of the memory that
is allocated and is able to determine whether that
memory is still useable. How?

Out of scope
or
Assign to null
Session 03 - Classes and Objects
Summary
• The key object-oriented programming
concepts: encapsulation, inheritance and
polymorphism
• The anatomy of a class, and how to declare
fields, methods, and constructors.
• Creating and using objects.
• How to instantiate an object, and, once
instantiated, how to use the dot operator to
access the object's instance variables and
methods. Session 03 - Classes and Objects

You might also like