Professional Documents
Culture Documents
Oop Lecture 06
Oop Lecture 06
Ralph Tambala
MUST . CSIT
Lecture 5 1 / 14
Outline
1 Inheritance
Object Class
Syntax
2 Composition
Composition vs. Inheritance
3 Aggregation
Lecture 5 2 / 14
Inheritance
Inheritance (1)
For example,
Lecture 5 3 / 14
Inheritance
Inheritance (2)
Inheritance in Java is a process that allows one object to inherit all of the
properties and behaviors of a parent object. The idea behind inheritance is
that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can use or modify the parent class’s
methods and fields. You can also add new methods and fields to your
current class.
Inheritance (3)
Object Class (1)
Class Object is the root of the class hierarchy. Every class has
Object as a superclass (parent). All objects, including arrays,
implement the methods of this class.
Every class in the Java system is a descendent (direct or indirect) of
the Object class. The Object class defines the basic state and
behavior that all objects must have, such as the ability to compare
oneself to another object, to convert to a string, to wait on a
condition variable, to notify other objects that a condition variable
has changed, and to return the object’s class.
We already looked at one important method that classes inherit from
the Object class (toString). The other methods include:
The equals Method – used to compare two objects for equality. This
method returns true if the objects are equal, false otherwise.
The getClass Method – Returns the Class class object of this object.
The Class class can further be used to get the metadata of this class.
Lecture 5 5 / 14
Inheritance Object Class
Inheritance (4)
Object Class (2)
Lecture 5 6 / 14
Inheritance Syntax
Inheritance (5)
Syntax
When you use the extends keyword, it means you are creating a new class
that is derived from an existing one.
Lecture 5 7 / 14
Inheritance Syntax
Inheritance (6)
Example
Staff is a User.
Inheritance (7)
Example cont...
Lecture 5 9 / 14
Composition
Composition (1)
Lecture 5 10 / 14
Composition Composition vs. Inheritance
Composition (2)
Composition vs. Inheritance
Lecture 5 11 / 14
Aggregation
Aggregation (1)
Lecture 5 12 / 14
Aggregation
Aggregation (2)
As seen in the code above, one can delete the car1 object and p1 will still
exists unlike in composition.
1 public class Passenger {
2 }
3
4 final class Car {
5 private Passenger passenger ;
6
7 void setPassenger ( Passenger passenger ) {
8 this . passenger = passenger ;
9 }
10
11 public static void main ( String [] args ) {
12 Car car1 = new Car () ; // exists independently
13 Passenger p1 = new Passenger () ;
14 car1 . setPassenger ( p1 ) ; // weak HAS A
15 }
16 }
Lecture 5 13 / 14
Aggregation
practice
Lecture 5 14 / 14