Objects and Classes Basic OO concepts Object, class, state, behavior, message Creating Java classes, objects, properties and methods Constructors Package Reference data type
Trang 1Web Programming with Java
Java Object-Oriented Programming
Huynh Huu Viet Email: viethh@uit.edu.vn
Department of Information Systems
Trang 2 Inheritance & Polymorphism
Some useful Java classes
Exception Handling, I/O
Readings & Exercise
Discussion
Trang 3Objects and Classes
Basic OO concepts
Object, class, state, behavior, message
Creating Java classes, objects,
properties and methods
Constructors
Package
Reference data type
Variable scope
Trang 4Basic OO concepts : Object
Object: any thing, which can be described by
State: property, or attribute
Behavior: function/action, or method: ask the object to perform a task
Example
A student, a desk, a circle, a button, and even a loan
Trang 5Basic OO concepts : Class
Class: a set of objects with common attributes and behaviors
An object is an instance of a class
Class is a template or blueprint that defines what an object's data and methods will be
Trang 6Basic OO concepts : Message
Objects interact (communicate) by
passing messages
Trang 7• Defining classes and their properties
• Manipulating classes/objects properties and behaviors
• Handling objects interactions
At execution time
Programs are executed through predefined
manipulations and interactions
Trang 8 A constructor without any parameter
If a programmer doesn’t define any constructor for a class, JRE will implicitly create a default
constructor
Trang 9Using Constructor
behaviors of an object when it is initially created
Three differences with methods:
Must have the same name as the class itself.
Do not have a return type - not even void.
object is created
ClassName() //no “void” or any other data
type {
… }
Trang 10Constructor Overloading
Like methods, constructors can be
overloaded
This offers greater flexibility and
convenience of creating objects
Trang 11Using Objects (1)
Object initialization
Using Member Variables
Member variable declaration
• Any where in a class, outside all methods
Used within the class
• Can be used/referenced anywhere directly
Used with objects
• Using the "." operator and preceded with object name
• Ex: myCircle.radius
ClassName objectName;
objectName = new ClassName();
Trang 12Using Objects: using methods
Defining methods
With a return value (type)
Without a return value (type) – void
Calling Methods
directly
Used with objects or outside the class
• Using the "." operator and preceded with object name
• Examples:
Trang 13The “main” Method
Following OOP guidelines, the use of the
“main” method should be deemphasized
The “main” method is merely a starting point of the application
There should not be too many statements in the main method
Using objects and methods effectively
Typically (and ideally), you only do these
things in the main method
Creating objects
Calling class/object methods
Trang 14 Packages are used to group classes
Four reasons for using packages
To locate classes
To avoid naming conflicts
To distribute software conveniently
Trang 16Using Package
Organizing your classes into packages
No duplicate class definition in the same
Trang 17referenced outside the default package
Trang 18Reference Data Type
Reference data type stores memory
address (reference) as its value
Objects are reference data type
Trang 20Variable Scope
Member variable
Something like a global
variable within the class
Local variable
Method parameter
Method level variable
Block level variable
A variable is effective at
its declaration level and
all sub-levels
Trang 21Variable Overriding
Variables cannot be declared twice at the same
level and its sub-levels
except class member variables (overridden by local
variables)
Use "this" keyword to refer to the class/object
itself to access (the overridden) member variables
this.title
this.couseId
this.getCourseInfo() //”this” can be used with method
It is good to use “this” explicitly for member
variables
Trang 22 Inheritance & Polymorphism
Some useful Java classes
Exception Handling, I/O
Readings & Exercise
Discussion
Trang 23 A concept to hide information or other details from the outside programs
Why? Should classes and methods
properties be available to other
programs (classes)?
Cohesion, modularity, integrity
Hides complexity, consistent and clear
interaction
Trang 24Access Modifiers
Encapsulation is implemented through the use of access modifiers/specifiers
private - completely encapsulated within the class
private int length;
default (no modifier) - within the same package
int length;
public - completely open
public int length;
(protected)
Trang 25Access Modifiers for Classes
If a class is defined public , then it can
scope)
public class Book { … }
Otherwise, if it is defined “default”,
then it can be referenced only by
those in the same package
class Book { … }
Note: any java source file can have
only one public class
Trang 26Java Access Modifiers
Trang 27 OO modeling
Class B is part of class A, or class A consists
of class B (one or many)
For example
Trang 28Aggregation Implementation
Aggregation is very common in object modeling and Java programs
In Java, this relationship is
implemented as a class member
variable is of a class/object type,
rather than primitive type
Trang 29Modeling One-to-One
Class A has a class B
A class (A)’s member property (p) is directly defined as another class (B) type
Trang 30Modeling One-to-Many
Class A has several class B’s
A class (A)’s member property (p) is
defined as a collection of class (B)
Trang 31 OO modeling
“Is-A” relationship between two classes
One class (child/subclass) will inherit
properties and behaviors of another class
(parent/super class)
For example, if “Faculty” is a
“Employee”
“Faculty” is the subclass
Trang 32Inheritance in Java
In Java class implementation
A subclass will inherit all available member
variables and methods of its super class
(availability is defined using access modifiers)
Use the statement “extends” to define inheritance
class Faculty extends Employee
{ … }
Using the super Keyword refers to the superclass
Trang 33Overriding Methods
Overriding method : the method is
defined in the subclass using the
same signature and same return type
as in its superclass
Overriding vs Overloading
Example: Section 9.4
Trang 34 Polymorphism allows methods to be used
generically for a wide range of object
arguments (generic programming)
Example: 9.7
Casting
Implicit casting: Object o = new Student();
Explicit casting: Student b = (Student) o
Demonstrating Polymorphism and Casting :
TestPolymorphismCasting.java
Trang 35Abstract Classes
Abstract classes
But you cannot create instances of abstract
An abstract method
Its implementation is provided by the
subclasses
be declared abstract
Example TestGeometricObject.java
Trang 36Interfaces
An interface is a classlike construct
that contains only constants and
Trang 37Interface vs Abstract class
Trang 38Multiple inheritance
Java allows
Only single inheritance for class extension
But multiple extensions for interfaces
Subinterface:
An interface can inherit other interfaces using the extends keyword
public class NewClass extends BaseClass
implementes Interface1, , InterfaceN{
}
public interface NewInterface extends Interface1, , InterfaceN {
// constants and abstract methods
Trang 39 Some useful Java classes
Exception Handling, I/O
Readings & Exercise
Discussion
Trang 40Some useful Java classes (1)
Trang 41Some useful Java classes (2)
StringBuilder/StringBuffer Class
Use StringBuffer if it may be accessed by
multiple tasks concurrently
StringBuilder (1.5 or above) is more efficient if
it is accessed by a single task
Modifying Strings in the Buffer with
methods:
insert()
delete()
Trang 42Some useful Java classes (3)
Reading text: java.util.Scanner
Scanner input = new Scanner(System.in);
Or Scanner input = new Scanner(new File(filename));
Trang 43Some useful Java classes (4)
Trang 44 Some useful Java classes
Exception Handling, I/O
Readings & Exercise
Discussion
Trang 45Exception Handling, I/O (1)
Run-time error occurs when a program
encounters an event that will break the
normal execution of the program
Traditional error handling is unstructured
and tightly binds the error handling code in the program flow
Java handles errors (exceptions)
in an object oriented way
with a systematical and structured mechanism
Trang 46Exception Handling, I/O (2)
Exception handling advantages
classified – easy learning and prediction
Flexible for user application to handle the
exception
Trang 47try {
statements that might cause errors }
statements to handle errors }
finally {
statements that will be executed under all conditions
}
Trang 48Handling Multiple Exceptions
Exception handling is very easy
effective when handling multiple
potential exceptions
Using “java.lang.Exception” to
capture all potential exceptions and deal with them consistently
Using multiple “catch” block to
capture specific exceptions and deal
Trang 49Typical Java Exceptions
Exceptions are defined using various classes
in various packages, but all inherit the
java.lang.Exception class
Trang 50Understanding Exception Handling
Java's exception-handling model with
3 operations:
Declaring an exception,
Trang 51Readings & Exercise
Trang 52Discussion