6. Aggregation and Inheritance
6. Aggregation and Inheritance
OOP: when modeling real world, there exist many obj types that have similar
or related attributes and behaviors.
Advantages
role name : if they dont have, by default is class name (uncapitalize the
first word)
Example in Java
class Point{
private int x, y;
public Point (){}
public Point (int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){ this.x = x;}
public int getX(){ return x;}
public void print(){
System.out.print("(" + x + ", "+ y + ") ");
}
}
class Quadrangle{
private Point[] corners = new Point[4];
public Quadrangle (Point p1, Point p2, Point p3, Point p4){
corners[0] = p1; corners[1] = p2;
corners[2] = p3; corners[3] = p4;
}
public Quadrangle(){
corners[0] = new Point();
corners[1] = new Point(0,1);
corners[2] = new Point(1,1);
corners[3] = new Point(1,0);
}
public void print(){
corners[0].print();
corners[1].print();
corners[2].print();
corners[3].print();
System.out.println();
}
}
public class Test {
public static void main(String arg[]){
Point p1 = new Point(2,3);
Point p2 = new Point(4,1);
Point p3 = new Point(5,1);
Point p4 = new Point(8,4);
Quadrangle q1 = new Quadrangle(p1,p2,p3,p4);
Quadrangle q2 = new Quadrangle();
q1.print();
q2.print();
}
}
3. Inheritance
A quadrangle has 4 points -> Aggregation
A square is an Quadrangle -> Inheritance
Inherit, Derive
Existing Class
New Class
What is Inheritance?
=> Polymorphism
Child classes
Is a kind of parent
Reuse by inheriting data and behavior of parent
Can be customized in two ways (or both):
Extension: add more new attributes/behaviors
Redefinition (Method Overriding): modify the behavior inheriting
from parent class.
Aggregation Inheritance
Reuse source code via Obj. Reuse source code via Class
Creating a reference to the obj of existing Creating new class by extending
classes in the new class existing classes.
Example
Inheritance hierarchy
Info
Note
Inheritance rules
Note
Example in Java
<SubClass> extends <SuperClass>
Obj Construction
Obj Destruction
The first cmd in constructor of a child class can explicit call the constructor
of its parent class
super(list_of_params);
Caution
This is obliged if the parent class does not have any default constructor
Constructor of the most basic class in the hierarchy tree will be called last,
but will finish first. The constructor of the derived class will finish at the last.