Part 05 - Object Oriented Programming
Part 05 - Object Oriented Programming
Creating Objects
Using Methods
Defining a Method
Polymorphism
Conversion of Data Types
Understanding Garbage Collection
Inheritance Polymorphism
Encapsulation
Information/implementation hiding
Inheritance
Polymorphism
class 2
sender target
setSomething()
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 14/155
Object Messaging Example
By itself the car is incapable of
activity. The car is only useful
when it is interacted with by
another object
Object 1 sends a message to
object 2 telling it to perform a
certain action +
In other words, the driver
presses the car’s gas pedal to
accelerate.
+draw()
“is-a” relations +erase()
+move()
The general classes can +setColor()
+getColor()
be specialized to
more specific classes
Circle Square Triangle
+flipVertical()
+flipHorizontal()
Polymorphism: +draw()
+erase()
+move()
– Ability to assume +setColor()
+getColor()
different forms or shapes.
– To exist in more than
one form Circle Square Triangle
object.
Objects are manipulated via references
Invoke object’s methods:
<object reference>.<method_name>(<arguments>)
26
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 26/155
The Elements of a class
// class body
}
28
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 28/155
Declaring Classes
Class Declaration Elements
Element Function
(Optional) An annotation (sometimes called meta-
@annotation data)
public (Optional) Class is publicly accessible
abstract (Optional) Class cannot be instantiated
final (Optional) Class cannot be subclassed
class NameOfClass Name of the class
Class instantiation
BankAccount knownAccount =
new BankAccount(accountNumber);
BankAccount namedAccount =
new BankAccount("My Checking Account");
...
public BankAccount(String name) {
super();
owner = name;
}
public BankAccount() {
this("TestName");
}
package com.megabank.models;
Access Levels
private Y N N N
no specifier Y Y N N
protected Y Y Y N
public Y Y Y Y
account.debit(50.5)
parameters
receiver
message
return method
access type name parameter list
modifier
not necessary
modifier.
You cannot override a static method to make it non-
static.
The overriding method and the overridden method
accessible.
If the overriding method has a throws clause in its
as well.
Each exception included in the throws clause of the
Use sparingly
You usually know how many arguments are possible
objectReference.methodName(); or
objectReference.methodName(argumentList);
System.out.println("Area of rectOne: " +
rectOne.area());
rectTwo.move(40, 72);
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 68/155
The Static Methods and Variables
The static modifier may be applied to a variable, a
method, and a block of code
A static element of a class is visible to all the instances
of the class
If one instance makes a change to it, all the instances
see that change
A static variable is initialized when a class is loaded,
An instance variable is initialized when an instance
which it exists
cannot be extended
If a final method cannot be overridden
pass-by-reference
Object-Oriented Programming 89
Inheritance
Based on "is-a" relationship Person
Subclass is derived
or inherits from superclass FullTimeStudent PartTimeStudent Manager
In essence:
Objects in the same class have the same set of
attributes (different values though) and operations
Objects of subclass have all members of superclass
plus some more
Objects of a subclass can also be treated as objects of
its superclass
Manager
-assistant: Employee
+setAssistant(emp: Employee)
//application code
...
Employee e = new Employee();
e.setName("John"); call to Person’s setName() method
System.out.print(e.getName());
e.setSalary(3.0);
private yes
package yes yes
(default)
protected yes yes yes
public yes yes yes yes
class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
} Explicit calls to
Shape(int, int)
class Circle extends Shape {
protected int radius;
public Circle(int x, int y, int radius) {
super(x, y);
this.radius = radius;
}
} // client code
Shape p = new Shape(10, 10);
Circle c2 = new Circle(10, 10, 5); // OK
class Shape {
protected int x, y;
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
} Error! Default constructor
Shape() is not found
class Circle extends Shape {
protected int radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}
class Shape {
protected int x, y;
public String toString() {
return "<" + x + "," + y + ">";
}
} Overriding Object's toString()
class Circle extends Point { New versions are used in
protected int radius; System.out.println()
public String toString() {
return super.toString() + "," + radius;
}
} // client code
Circle c = new Circle();
System.out.println(c);
Examples: +area()
+perimeter()
+area()
+perimeter()
+area()
+perimeter()
Animal, Cat, Cow, Dog,…
An Animal object makes no sense
What sort of sound does it make?
Shape, Point, Rectangle, Triangle, Circle
What does a generic Shape look like?
How to draw it?
Solution: make it an abstract base class
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 117/155
Abstract Classes
Abstract classes cannot be instantiated – they are
intended to be a superclass for other classes
abstract methods have no implementation
If a class has one or more abstract methods, it is
abstract, and must be declared so
Concrete classes have full implementations and can be
instantiated
119
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 119/155
public class CartesianPoint {
private int x;
private int y;
public CartesianPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
} public abstract class Shape {
protected CartesianPoint location;
public Shape(CartesianPoint location) {
this.location = location;
}
public abstract double area();
public abstract double perimeter();
public abstract void draw();
}
class MyOuter {
class MyInner { }
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 129/155
interface Cookable { Anonymous Inner
public void cook(); Classes with Interface
}
class Food {
Cookable c = new Cookable() {
public void cook() {
System.out.println("anonymous cookable implementer");
}
};
}
interface Foo {
void foof();
}
class Bar {
void doStuff(Foo f) { }
}
Multiple Interfaces:
If a class implements multiple interfaces, the interfaces
are all listed, separated by commas
public class Directory implements File, Secure {
...
}
Stipulations
Only objects whose class implements that interface can
be bound to that variable
Only messages defined by the interface can be used
Interfaces cannot appear in a new expression
@Override
public int compareTo(Object o) {
Employee emp = (Employee)o;
return this.getName().compareTo(emp.getName());
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 147/155
Sort Array of Comparable Objects
public class EmployeeSortTest {
public static void main(String[] args) {
Employee[] staffs = new Employee[3];
Arrays.sort(staffs);
Arithmetic Conversion
boolean types.
A non-boolean type can be converted into another