Download OBJECT ORIENTED PROGRAMMING

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
OBJECT ORIENTED
PROGRAMMING
Course 4
Loredana STANCIU
[email protected]
Room B613
INHERITANCE
A class that is derived from another class is
called a subclass (also a derived class,
extended class, or child class).
´ The class from which the subclass is derived is
called a superclass (also a base class or a
parentt class).
l )
´ Descendent — a class derived from other class
´
INHERITANCE
Every class has one and only one direct
superclass (single inheritance).
´ A subclass inherits all the members (fields,
methods and nested classes) from its
methods,
superclass
´ The constructor of the superclass is not
inhereted but can be invoked from the subclass
´
THE JAVA PLATFORM CLASS HIERARCHY
Every class is implicitly a subclass of Object
(java.lang package)
´ Defines and implements behavior common to
all classes
´ Hierarchy of classes
´
´
http://java.sun.com/javase/6/docs/api/java/
http://java
sun com/javase/6/docs/api/java/
lang/Object.html
THE JAVA PLATFORM CLASS HIERARCHY
INHERITANCE - EXEMPLE
´
´
´
´
´
´
´
´
´
class
l
P l
Polygon
{
protected double[ ] sides;
public
bli P
Polygon(int
l
(i t n)
) {
¹ sides = new double[n] }
public double perimeter( ) {
double s=0;
for(int i=0;i<sides.length;i++)
« s+=sides[i];
return s;
}
}
INHERITANCE - EXEMPLE
´
´
´
´
´
´
´
´
´
´
class
l
Rectangle
R
t
l extends
t d Polygon
P l
{
public Rectangle(double L, double h){
super(4);
(4)
sides[0] = sides[2] = L;
sides[1]
1 = sides[3]
3 = h;
}
public double area( ){
return sides[0]*sides[1];
}
}
INHERITANCE - EXEMPLE
´
´
´
´
´
´
´
class
l
Cli t {
Client
public static void main (String [] args){
R t
Rectangle
l r1
1 = new Rectangle
R t
l (4,
(4 2)
2);
System.out.println(“The perimeter
is:” + r1
r1.perimeter();
perimeter();
System.out.println(“The area
is:” + r1
is:
r1.area();
area();
}
}
SUBCLASSES
Inherits all of the public and protected
members of its parent, no matter what
package the subclass is in
´ In the same package as its parent,
parent it inherits
the package-private members of the parent
´ The inherited fields and methods can be used
directlyy
´ Can declare a field in the subclass with the
same name as the one in the superclass —
hiding it
´
SUBCLASSES
Can have new fields and new methods
´ Create a new instance method in the subclass
that has the same signature as the one in the
superclass
supe
c ass — o
overriding
e d g
´ Create a new static method in the subclass
th t has
that
h the
th same signature
ig t
as the
th one in
i the
th
superclass — hiding
´
SUBCLASSES
Does not inherit the private members of its
parent class — accessed only if the superclass
has public or protected methods
´ Write a subclass constructor that invokes the
constructor of the superclass
´
CASTING OBJECTS
« Rectangle
g
rt = new Rectangle(2,3);
g
Rectangle Å Polygon Å Object
´ rt
t is
i aR
Rectangle,
t
l a Polygon,
P l
and
d an Object
Obj t
´
´
Casting
g shows the use of an object
j
of one
type in place of another type (permitted by
inheritance and implementations)
« Object
´
obj = new Rectangle(2,3);
implicit casting
CASTING OBJECTS
« Rectangle
g
´
rt = obj;
j
compile-time error
« Rectangle
R t
l
rt
t = (Rectangle)
(R t
l ) obj;
bj
explicit casting
´ the instanceof operator — a logical test to the
type of a particular object
´ if (obj instanceof Rectangle)
´ {Rectangle rt = (Rectangle) obj;
´}
´
OVERRIDING AND HIDING METHODS
Instance Methods
´ An instance method in a subclass with the
same signature
ig t
as an instance
i t
method
th d in
i th
the
superclass overrides the superclass's
method.
´ Allows a class to inherit from a superclass
whose behavior is "close enough" and then to
modify behavior as needed
´
OVERRIDING AND HIDING METHODS
Class Methods
´ If a subclass defines a class method with the
same signature
ig t
as a class
l
method
th d in
i the
th
superclass, the method in the subclass hides
the one in the superclass.
´ The distinction between hiding and overriding:
´
« The
version of the overridden method that gets
invoked is the one in the subclass
« The version of the hidden method that gets
invoked depends on whether it is invoked from
the superclass or the subclass
OVERRIDING AND HIDING METHODS
´
public class Animal {
« public static void testClassMethod() {
² System.out.println("The class method in
Animal.");
« }
« public void testInstanceMethod() {
² System.out.println("The instance method
in Animal.");
« }
´
}
OVERRIDING AND HIDING METHODS
´
´
public class Cat extends Animal {
« public static void testClassMethod() {
² System.out.println("The class method in
Cat.");
« }
« public void testInstanceMethod() {
² System.out.println("The instance method
in Cat.");
« }
}
OVERRIDING AND HIDING METHODS
´
public class Client{
« public static void main(String[ ] args) {
² Cat myCat = new Cat();
² Animal myAnimal = myCat;
² Animal.testClassMethod();
² myAnimal.testInstanceMethod();
« }}
The output:
´ The class method in Animal.
Animal -- hidden
´ The instance method in Cat. -- overrided
´
OVERRIDING AND OVERLOADING
Override — a method having the same
signature (name, plus the number and the
type of its parameters) and return type
´ Overload — a method having the same name
and return type but different list of
parameters
t
´
USING THE KEYWORD SUPER
´
´
´
Used to invoke the superclass’s
p
members
public class Superclass {
« p
public void p
printMethod()
() {
System.out.println("Printed in
Superclass.");
« }}
public class Subclass extends Superclass {
« public void printMethod(){
² super.printMethod();
² System.out.println("Printed in
Subclass");
« }}
USING THE KEYWORD SUPER
´
public class Client{
« public static void main(String[] args) {
« Subclass s = new Subclass();
« s.printMethod();
« } }
The output:
´ Printed in Superclass.
´ Printed in Subclass
´
SUBCLASS CONSTRUCTORS
´
´
´
´
public Rectangle(double L, double h){
super(4);
sides[0] = sides[2] = L;
sides[1] = sides[3] = h;}
Invocation of a superclass constructor must
be the first line in the subclass constructor.
´ The syntax for calling a superclass
constructor:
´ super() or super(parameter list)
´
OBJECT AS A SUPERCLASS
´
Every class is a descendant, direct or indirect
«p
protected
Object
j
clone()
() throws
CloneNotSupportedException
´
Creates and returns a copy of this object.
object
« public
´
boolean equals(Object obj)
Indicates whether some other object is "equal
to" this one.
OBJECT AS A SUPERCLASS
« protected
´
Called by the garbage collector on an object
« public
´
int hashCode()
R t
Returns
a hash
h h code
d value
l for
f the
th object.
bj t
« public
´
final Class getClass()
Returns the runtime class of an object.
j
« public
´
void finalize() throws Throwable
String toString()
Returns a string representation of the object.
OBJECT AS A SUPERCLASS
´
Synchronizing the activities of independently
running threads in a program
« public
bli
final
fi l void
id notify()
if ()
« public final void notifyAll()
« public final void wait()
« public final void wait(long timeout)
« public final void wait(long timeout, int nanos)
THE CLONE() METHOD
´
A class, or one of its superclasses, implements
the Cloneable interface
« aCloneableObject.clone();
protected Object clone() throws
CloneNotSupportedException
´ public Object clone() throws
C o e otSuppo ted cept o
CloneNotSupportedException
´ Add implements Cloneable to your class's
declaration
´
THE EQUALS() METHOD
´
´
´
Compares
p
two objects
j
for equality
q
y and returns
true if they are equal
public class Book {
« ...
« public boolean equals(Object obj) {
² if (obj instanceof Book)
¹ return
ISBN.equals((Book)obj.getISBN());
² else return false;
« }
}
THE EQUALS() METHOD
´
´
´
´
Book firstBook = new Book("0201914670");
Book secondBook = new Book("0201914670");
if (firstBook.equals(secondBook))
« System.out.println("objects are equal");
else
« System.out.println("objects are not
equal");
The output:
´ objects are equal
´
THE FINALIZE() METHOD
´
´
´
´
´
´
May be invoked
Ma
in oked on an object when
hen it becomes
garbage
class
l
M Cl
MyClass{
{
private long a;
public
bli MyClass(long
l
(l
x){
){
« a=x;
« System.out.println(“Object
“ +a+ “ was
created”);}
protected
t t d void
id fi
finalize()
li () th
throws Throwable{
Th
bl {
« System.out.println(“Object “ +a+ “ was
destroyed );}
destroyed”);}
}
THE FINALIZE() METHOD
´
´
class ClientClass{
« public static void main (String [ ] args){
² MyClass a;
² long no_obj = 50000;
² for(
f ( l
long i=4;i<no_obj;i++)
i 4 i<
bj i++)
¹ { a=new MyClass(i);
¹ a=null;}
ll }
}
THE GETCLASS() METHOD
´
´
You cannot override getClass()
Returns a Class object, which has methods you can
use to get information about the class:
«
«
«
Its name (getSimpleName())
its superclass (getSuperclass())
the interfaces it implements (getInterfaces())
´
void printClassName(Object obj) {
« System.out.println("The
S t
t
i tl ("Th object's
bj t' class
l
i
is
“ + obj.getClass().getSimpleName());
}
´
http://java.sun.com/javase/6/docs/api/java/lang/Class.html
´
WRITING FINAL CLASSES AND METHODS
´
´
´
Indicate that the method cannot be overridden
by subclasses
class ChessAlgorithm {
« enum ChessPlayer { WHITE, BLACK }
« ...
« final ChessPlayer getFirstPlayer() {
² return ChessPlayer.WHITE;
ChessPlayer WHITE; }
« ...}
An entire
A
ti class
l
final
fi l — when
h creating
ti g an
immutable class like the String class
ABSTRACT METHODS AND CLASSES
´
An abstract class:
«a
class that is declared abstract
« cannot be instantiated, but they can be inhereted
´
An abstract method — a method that is declared
without an implementation
« abstract
´
void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class
itself must be declared abstract
ABSTRACT METHODS AND CLASSES
´
´
´
public
bli abstract
b t
t class
l
G
GraphicObject
hi Obj t {
« // declare fields
« // d
declare
l
non-abstract
b t
t methods
th d
« abstract void draw();
}
The subclass has to provide implementations for
all of the abstract methods — abstract
ABSTRACT METHODS AND CLASSES
´
Graphic
G
hi objects:
bj
« states (for example: position, orientation, line color,
fill color)
« behaviors ((for example:
p moveTo, rotate, resize, draw))
ABSTRACT METHODS AND CLASSES
´
´
abstract
b t
t class
l
G
GraphicObject
hi Obj t {
« int x, y;
« ...
« void moveTo(int newX, int newY)
² { ... }
« abstract void draw();
« abstract void resize();
}
ABSTRACT METHODS AND CLASSES
´
´
´
´
class
l
Ci
Circle
l extends
t d GraphicObject
G
hi Obj t {
« void draw() { ... }
« void
id resize()
i () { ... }
}
class Rectangle extends GraphicObject {
« void draw() { ... }
« void resize() { ... }
}
WHAT IS POLYMORPHISM?
The ability of one object to be treated,
treated or
used, like another
´ A powerful tool allowing architectures to be:
´
« designed
and built that will be flexible enough to
change with businesses' needs,
« stable enough not to require redesign and rebuild
on a regular basis
OVERLOADING POLYMORPHISM
Occurs when a child class overrides the
method implementation of the parent class
´ Different child classes have different
behaviors based on some intrinsic
characteristic of the child class
´
´
´
´
p
public
class Drink{
{
…
« public void ingest()
« {…}
}
OVERLOADING POLYMORPHISM
´
´
´
´
´
´
p
{
public class Milk extends Drink{
…
« p
public void ingest()
g
()
« {//action specific}
}
public class Vodka extends Drink{
…
« public void ingest()
« {//action specific}
}
INCLUSION POLYMORPHISM
A child class inherits its method substance
from the base or parent class
´ Enables objects or systems that would
previouslyy have used the base class to use the
child classes with equivalent results
´
PARAMETRIC POLYMORPHISM
A class or classes implement methods that
are the same in signature except for the
parameters passed to the method
´ One class can handle many
y different types
y
of
arguments to a specific method
´
PARAMETRIC POLYMORPHISM
´
´
p
public class DataDraw {
« ...
« p
public void draw(String
(
g s)
)
« { ... }
« pub
public
c void
o d draw(int
d a ( t i)
)
« { ... }
« public void draw(double f)
« { ... }
« public void draw(int i, double f)
« { ... }
}
COERCION POLYMORPHISM
´
´
´
´
A primitive or object type is cast or "coerced"
coerced into
being another primitive type or object type
Rectangle rt = (Rectangle) obj;
float f = 3.4;
int I = (int) f;
REFERENCES
´
´
The Java
Th
J
Tutorials.
T
i l Learning
L
i the
h Java
J
LLanguage.
http://java.sun.com/docs/books/tutorial/java/IandI
/ b l
/subclasses.html
h l
The Power of Polymorphism, http://www2.syscon.com/itsg/virtualcd/java/archives/0508/barnab
ee/index.html