CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVAclass followed by a class name and braces surrounding the declaration and the data of objects of the class... CLASSES, OBJECTS, VARIABLES,
Trang 1CHAPTER 2
Fundamentals of Object Orientation
Trang 4In this chapter, we review:
(OO) programming in order to understand
how such programming is different from
nonobject-oriented programming
applied to elegant software design
inheritance
Trang 5Unified Modeling Language (UML) class
diagrams
options (e.g., public and private) of data,
methods, and classes, as they apply to Java
Trang 6OOP VS NON–OOP
Non OOP:
• A program is usually process-oriented or data-oriented
In such programs, there are typically data globally
available and procedures globally available
• The main program, or its subprograms, are in control and manipulate the data.
• The main program, through its subprograms, has all the
“intelligence” or behavior in the program and the data has no intelligence
• The main program and its subprograms are responsible
Trang 7OOP VS NON–OOP
OOP:
• A program is partitioned into a set of
communicating objects Each object encapsulates all the behavior and knowledge relating to one
concept
• When an object needs something from another object, it sends it a message to the other object, which then performs some action and possibly
Trang 8OOP VS NON–OOP
typically creates a few objects and start them communicating with each other
Ex: Windows, menus, buttons are objects
objects share the work and the
responsibilities, should seem familiar in that
it is the way humans typically interact with
each other
Trang 9OOP VS NON–OOP
Object-Oriented Languages
• We call a programming language object-oriented
if the language supports classes, objects,
messages, inheritance, and (subtype)
polymorphism.
• In an OO programming language, classes can be viewed as templates for objects that describe a certain type of behavior or a certain set of
Trang 10OOP VS NON–OOP
Object-Oriented Languages
of a class An object’s associated class defines the type of data the object maintains and its behavior or responsibilities toward that data
(their own state) to maintain
Trang 11OOP VS NON–OOP
Object-Oriented Languages
• The way objects communicate and get each other
to perform some action is by sending messages
to each other
• By sending a message to another object, the first object causes the second object to execute some code That code is actually a procedure—which in object-oriented languages is called a method —
Trang 12OOP VS NON–OOP
Advantages of OO Programming
objects Therefore, it is easier to keep things in
small manageable units and to understand
how the units affect each other
Trang 13OOP VS NON–OOP
Advantages of OO Programming
structure of the global data in a non-OO
that access that data
little global data and instead stores the data in
Trang 14OOP VS NON–OOP
Advantages of OO Programming
• If a programmer decides that a particular object
is working too inefficiently, the programmer can redesign the object’s behavior to be more
efficient without affecting the rest of the system, thus supporting the maintainability of the
software
• Since each object has typically one small
well-defined role and carries the data it needs with it,
it is usually easier to reuse these objects in other situations.
Trang 15OOP VS NON–OOP
Advantages of OO Programming
readability, reusability, and maintainability of the software
Trang 16CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVA
class followed by a class name and braces
surrounding the declaration and
the data of objects of the class
Trang 17CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVApublic class Person
{
private String name;
private Date birthdate;
public Person(String name, Date birthdate)
{
this.name = name;
this.birthdate = birthdate;
}
Trang 18CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVApublic String getName()
Trang 19CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVA
construct a Person object using the
constructor, as in
Person firstPerson =
new Person(“Adam”, new Date(0));
and then send the object a message, such as
String firstPersonName =
Trang 20CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVA
• In order to execute their methods properly, most objects need to store data This data is stored in
instance variables in Java.
• Instance variables differ from local variables They exist and store data during the whole life of the object.
• In Java, only variables of a primitive type actually store their data in the variable For all variables of
an object type, the variables store a reference to the data.
Trang 21CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVA
most objects need to store data This data is
of the object
Trang 22CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVA
actually store their data in the variable For all variables of an object type, the variables store
a reference to the data
Trang 23CLASSES, OBJECTS, VARIABLES, AND METHODS IN JAVA
• The methods of a class correspond to
messages that objects can send to an object of this class These methods correspond to the
behavior of objects of this class They can also
this class can provide for other objects
Trang 24CLASS METHODS AND VARIABLES IN JAVA
methods
an object of the class and class variables can
Trang 25CLASS METHODS AND VARIABLES IN JAVA
constants In Java, a constant is indicated by
public final static int C = 299792458;
Trang 26CLASS METHODS AND VARIABLES IN JAVA
• Class methods can be thought of as methods that are not a form of message passing to objects of that class and instead can be invoked
independently of any objects of the class
• In general, class methods are useful when objects
of that class are stateless (i.e., have no instance variables) or when some of the methods do not use the state of the objects and instead merely manipulate the data passed in as parameters
Trang 27CLASS METHODS AND VARIABLES IN JAVA
Math class
double y = Math.sin(x);
defining a Set class There are (at least) two
public Set intersect(Set otherSet)
Trang 28CLASS METHODS AND VARIABLES IN JAVA
• Usages:
Set intersection = s1.intersect(s2);
or
Set intersection = Set.intersect(s1, s2);
Trang 29CLASS METHODS AND VARIABLES IN JAVA
• Class methods can be thought of as methods that are not a form of message passing to objects of that class and instead can be invoked
independently of any objects of the class
• In general, class methods are useful when objects
of that class are stateless (i.e., have no instance variables) or when some of the methods do not use the state of the objects and instead merely
Trang 30INTRODUCTION TO UML CLASS
DIAGRAMS
be very helpful
called the Unified Modeling Language for such diagrams
UML 2.0, among which are class diagrams,
state diagrams, and sequence diagrams
Trang 31INTRODUCTION TO UML CLASS
DIAGRAMS
modeling language For ex:
Trang 32INTRODUCTION TO UML CLASS
DIAGRAMS
interfaces and the relationships between
them
classes and relationships rather than a
dynamic view of the interactions among
objects of those classes
three sections
Trang 33INTRODUCTION TO UML CLASS
DIAGRAMS
• A class is represented by a box divided into three sections
– The top section gives the name of the class
– The middle section gives the attributes or properties held by objects of the class These properties are
abstractions of the data or state of an object and so are usually implemented using instance variables
– The bottom section gives the operations of a class,
Trang 34CLASS METHODS AND VARIABLES IN JAVA
Trang 35IMPLEMENTATION INHERITANCE
programming is “implementation inheritance”
or “subclassing,” which greatly increases the
reusability of classes and also minimizes the duplication of code
specialization and generalization
Trang 36IMPLEMENTATION INHERITANCE
Specialization
Creating a drawing program in which
rectangles can grow, shrink, or move around
on a panel under the control of the user
stores the relevant information about the
rectangle, such as its size and position
Trang 37IMPLEMENTATION INHERITANCE
Specialization
satisfying our needs
setCenter(int x, int y) method and Rectangle
minimal effort?
Trang 38IMPLEMENTATION INHERITANCE
Specialization
1 We could modify the class (add methods)
2 We could copy the Rectangle class code and
insert it into a new class EnhancedRectangleand then add the new code
to take, but not in either of these ways Both
of these approaches have inelegant aspects
Trang 39IMPLEMENTATION INHERITANCE
Specialization
works if only the compiled code, and not the source code, for the Rectangle class is
available
inheritance can be used
Trang 40IMPLEMENTATION INHERITANCE
Specialization
• Java (and other OO languages) allows the
programmer to define one class as a subclass of another class (which makes the second class a
superclass of the first class)
• A subclass inherits all the features (all the
variables and methods, but not the constructors)
of the superclass, which means all those features are automatically included in the subclass and, if not declared private, are accessible in the
subclass
Trang 41IMPLEMENTATION INHERITANCE
Specialization
subclass to the superclass is
Trang 42IMPLEMENTATION INHERITANCE
public class EnhancedRectangle extends Rectangle {
public EnhancedRectangle(int x, int y, int w, int h)
Trang 43IMPLEMENTATION INHERITANCE
Specialization
• This declaration makes EnhancedRectangle a
subclass of Rectangle and makes Rectangle a
superclass of EnhancedRectangle Because it is a subclass, the new EnhancedRectangle class
inherits all the methods and all the data in the
Rectangle class
• Note that since constructors are not inherited ,
Trang 44IMPLEMENTATION INHERITANCE
Specialization
Trang 45IMPLEMENTATION INHERITANCE
Specialization
class can use it as follows:
EnhancedRectangle rectangle = new
EnhancedRectangle(1, 2, 50, 60);
rectangle.setLocation(10, 10);
//inherited method
Trang 46IMPLEMENTATION INHERITANCE
Specialization
• Note that EnhancedRectangle objects behave as
if all methods inherited from the Rectangle class
had been defined in their class.
• In this way, subclassing provides a way to reuse the code and data of an existing class to create a
new class that is identical except that it has more features (data and/or behavior)
• This process of extending an existing class by
adding new features is called using inheritance for specialization.
Trang 47IMPLEMENTATION INHERITANCE
The Object Superclass in Java
• All Java classes that do not explicitly extend
another class implicitly extend the Object class
• Therefore, all Java classes extend the Object class
either directly or indirectly via one or more
intermediate classes in an inheritance chain
• This means that your classes will automatically inherit the methods in the Object class: clone,
Trang 48IMPLEMENTATION INHERITANCE
Specialization
program using the Java Swing package
Suppose that the program allows the user to
borders and stores all drawn ovals in a
collection of Oval objects
how to draw themselves:
Trang 50return new Point(x,y); } // other methods
}
Trang 51IMPLEMENTATION INHERITANCE
to enhance the program to allow the user to
Trang 52IMPLEMENTATION INHERITANCE
Specialization
job done in an elegant way?
(How many ways? Which way is best?)
Trang 53IMPLEMENTATION INHERITANCE
Specialization
1 She could ignore the Oval class and design her own
FilledOval class that she implements from scratch.
2 She could realize that the Oval is exactly what she
needs except that Ovals do not have black interiors when drawn, and so she could copy and paste the
Oval class source code into a new FilledOval class and then make small changes to it to change the way it
draws itself.
3 She could use implementation inheritance and
Trang 54IMPLEMENTATION INHERITANCE
Specialization - overriding
methods and data in the Oval class
FilledOval to inherit all the behavior of Oval She wants her class to have a slightly different implementation of the same draw method
implementation of draw
Trang 55IMPLEMENTATION INHERITANCE
public class FilledOval extends Oval {
public FilledOval(int x, int y, int w, int h) {
super(x, y, w, h);
} public void draw(Graphics g) {
g.fillOval(x, y, w, h);
}
Trang 56IMPLEMENTATION INHERITANCE
Specialization
didn’t want to enhance the Oval class by
adding new attributes or behavior, but instead
slightly differently
Trang 58IMPLEMENTATION INHERITANCE
Generalization
keeps track of all its current customers
customers and business customers, the
designers of the billing system created two
unrelated classes, BusinessCustomer and
HumanCustomer
Trang 59IMPLEMENTATION INHERITANCE
Generalization
keeps track of all its current customers,
including human customers and business
customers
Trang 60IMPLEMENTATION INHERITANCE
Generalization
becauseboth of these classes might have
some similar data and some identical
methods
introduce a new Customer class that is a
superclass of both the BusinessCustomer and HumanCustomer classes
Trang 61IMPLEMENTATION INHERITANCE
Generalization
Trang 62IMPLEMENTATION INHERITANCE
Generalization
want the user to create any Customer objects, since that class has been created merely as a place to put common features to avoid
duplication One way to prevent creation of
Customer objects is to declare the class
“abstract.”
Trang 63String humanName = human.getName();
String businessName = business.getName();
Trang 64IMPLEMENTATION INHERITANCE
Generalization
be used to avoid code and data duplication
among several classes by creating a superclass
to those classes and moving the duplicate
code and data up into that superclass, which is
commonly abstract
generalization
Trang 65IMPLEMENTATION INHERITANCE
Single Inheritance in Java
Trang 66IMPLEMENTATION INHERITANCE
Multiple Inheritance might cause ambiguity
Trang 67TYPES, SUBTYPES, AND INTERFACE INHERITANCE
Type
operations that can be performed on them
– Primitive types.
– Classes.
– Interfaces.
Trang 68TYPES, SUBTYPES, AND INTERFACE INHERITANCE
Interface
of operations All objects whose classes
set of objects of that type Ex:
public interface Runnable
{
public void run();
}
Trang 69TYPES, SUBTYPES, AND INTERFACE INHERITANCEInterface
• The set of objects of type Runnable consists of all objects of all classes that implement Runnable.
public class SimpleRunner implements Runnable
{
public void run() {
System.out.println(“I’m running.” ); }
Trang 70TYPES, SUBTYPES, AND INTERFACE INHERITANCEInterface
• The class
SimpleRunner defines
and implements a
method run() of the form
required by the Runnable
interface and the class
explicitly declares that it
“implements Runnable.”
Trang 71TYPES, SUBTYPES, AND INTERFACE INHERITANCE
Interface
inherit from them similar to the way
inheritance works with classes
public interface Movable extends Runnable {
public void walk();
Trang 72TYPES, SUBTYPES, AND INTERFACE INHERITANCE
Polymorphism
a variable of one type to store an object of a subtype
Runnable r = new SimpleRunner();
legally used wherever an object of a supertype
Trang 73TYPES, SUBTYPES, AND INTERFACE INHERITANCE
important concepts in object orientation and
is one of the main things that makes OO
languages so useful
extensively In fact, the Java 1.5 API includes over 1000 interfaces Everywhere one of these Java interfaces is used, polymorphism is also
Trang 74The Value of Polymorphism
program
java.util.LinkedList class extensively as the
collection class in a large software system
uses of the LinkedList class with a different
collection class such as the ArrayList class
Trang 75The Value of Polymorphism
require significant changes to the system
with such a replacement in mind, you would have to make a lot of changes
work, but this whole process might need to be repeated again (if it is later found that