0% found this document useful (0 votes)
12 views18 pages

CH 04 OOP Inheritance

The document discusses object-oriented programming concepts related to inheritance. It defines inheritance as creating a new class from an existing class, where the new subclass inherits and extends the data and behaviors of the parent superclass. The document provides examples of inheritance hierarchies and relationships between superclasses and subclasses. It describes how subclasses can inherit, override, or extend the methods and fields of their parent superclasses. An example inheritance hierarchy of Points and Circles classes is presented to illustrate these concepts.

Uploaded by

sondos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views18 pages

CH 04 OOP Inheritance

The document discusses object-oriented programming concepts related to inheritance. It defines inheritance as creating a new class from an existing class, where the new subclass inherits and extends the data and behaviors of the parent superclass. The document provides examples of inheritance hierarchies and relationships between superclasses and subclasses. It describes how subclasses can inherit, override, or extend the methods and fields of their parent superclasses. An example inheritance hierarchy of Points and Circles classes is presented to illustrate these concepts.

Uploaded by

sondos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Object Oriented Programming

10636212

Dr. Ashraf Armoush

© 2020 Dr. Ashraf Armoush

Chapter 04:

Object Oriented Programming

- Inheritance -

© 2020 Dr. Ashraf Armoush


Inheritance
• Software reusability
• Create new class from existing class
– Absorb existing class’s data and behaviors
– Enhance with new capabilities

• A class that is derived from another class is called a subclass


(also a derived, extended , or child class).
• The class from which the subclass is derived is called
a superclass (also a base class or a parent class).
• Subclass extends superclass
• Subclass
– More specialized group of objects
– Behaviors inherited from superclass
» Can customize
• Each subclass can become the superclass for future subclasses.
© 2020 Dr. Ashraf Armoush , An-Najah National University 3

Inheritance (cont.)
• Class hierarchy
– Direct superclass
• Inherited explicitly (one level up hierarchy)
– Indirect superclass
• Inherited two or more levels up hierarchy
– Single inheritance
• Inherits from one superclass
– Multiple inheritance
• Inherits from multiple superclasses
– Java does not support multiple inheritance

© 2020 Dr. Ashraf Armoush , An-Najah National University 4


is-a Relationship
A commonly employed rule to understand when inheritance is
an appropriate SW technique is known as is-a relationship.

• To determine if the class X


inherits from class Y, form the
sentence:
"An X is a Y".
• If this sounds correct and if it
seems to match everyday
experience, then X and Y have
a is-a relationship. An apple is a fruit

© 2020 Dr. Ashraf Armoush , An-Najah National University 5

Superclasses and Subclasses


• Superclasses and subclasses
– Object of one class “is an” object of another class
• Example: Rectangle is quadrilateral.
– Class Rectangle inherits from class Quadrilateral
– Quadrilateral: superclass
– Rectangle: subclass
– Superclass typically represents larger set of
objects than subclasses
• Example:
– superclass: Vehicle
» Cars, trucks, boats, bicycles, …
– subclass: Car
» Smaller, more-specific subset of vehicles

© 2020 Dr. Ashraf Armoush , An-Najah National University 6


Inheritance Hierarchy
• Inheritance relationships: tree-like hierarchy structure

CommunityMember

Employee Student Alumnus

Faculty Staff

Administrator Teacher

Inheritance hierarchy for university CommunityMembers

© 2020 Dr. Ashraf Armoush , An-Najah National University 7

Inheritance Hierarchy

Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron

Inheritance hierarchy for Shapes.

© 2020 Dr. Ashraf Armoush , An-Najah National University 8


protected Members
• protected access
– Intermediate level of protection between
public and private
– protected members accessible to
• superclass members
• subclass members
• Class members in the same package
– Subclass access superclass member
• Keyword super and a dot (.)

© 2020 Dr. Ashraf Armoush , An-Najah National University 9

Relationship between Superclasses and Subclasses

• Using protected instance variables


– Advantages
• subclasses can modify values directly
• Slight increase in performance
– Avoid set/get function call overhead
– Disadvantages
• No validity checking
– subclass can assign illegal value
• Implementation dependent
– subclass methods more likely dependent on superclass
implementation
– superclass implementation changes may result in subclass
modifications

© 2020 Dr. Ashraf Armoush , An-Najah National University 10


What You Can Do in a Subclass
• A subclass inherits all of the public and protected members of its
parent, no matter what package the subclass is in.

• If the subclass is in the same package as its parent, it also inherits


the package-access members of the parent.

• You can use the inherited members as is, replace them, hide them,
or supplement them with new members.

• The inherited fields can be used directly, just like any other fields.

• You can declare a field in the subclass with the same name as the
one in the superclass, thus hiding it (not recommended).

• You can declare new fields in the subclass that are not in the
superclass.

© 2020 Dr. Ashraf Armoush , An-Najah National University 11

What You Can Do in a Subclass (cont.)


• The inherited methods can be used directly as they are.

• You can write a new instance method in the subclass that has the
same signature as the one in the superclass, thus overriding it.

• You can write a new static method in the subclass that has the
same signature as the one in the superclass, thus hiding it.

• You can declare new methods in the subclass that are not in the
superclass.

• You can write a subclass constructor that invokes the constructor of


the superclass, either implicitly or by using the keyword super.

© 2020 Dr. Ashraf Armoush , An-Najah National University 12


Example
Point/circle inheritance hierarchy
• Point
– x-y coordinate pair
– Methods:
• Circle
– x-y coordinate pair
– Radius

© 2020 Dr. Ashraf Armoush , An-Najah National University 13

public class Point extends Object {


protected int x, y; // coordinates of the Point
public Point() // no-argument constructor
{
Point x = 0;
y = 0;
Class }
System.out.println( "Point constructor: " + this );

public Point( int xCoordinate, int yCoordinate ) // constructor


{
x = xCoordinate;
y = yCoordinate;
System.out.println( "Point constructor: " + this );
}
protected void finalize() // finalizer
{
System.out.println( "Point finalizer: " + this );
}
// convert Point into a String representation
public String toString()
{
return "[" + x + ", " + y + "]";
}
} // end class Point

© 2020 Dr. Ashraf Armoush , An-Najah National University 14


Circle Class
public class Circle extends Point { // inherits from Point
protected double radius;

// no-argument constructor
public Circle()
{
// implicit call to superclass constructor here
radius = 0;
System.out.println( "Circle constructor: " + this );
}

// Constructor
public Circle( double circleRadius, int xCoordinate, int yCoordinate
)
{
// call superclass constructor
super( xCoordinate, yCoordinate );
radius = circleRadius;
System.out.println( "Circle constructor: " + this);
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 15

Circle Class (cont.)


protected void finalize() // finalizer
{
System.out.println( " Circle finalizer: " + this );
}
// convert the circle into a String representation
public String toString()
{
return "Center = " + super.toString() +
"; Radius = " + radius;

}
} // end class Circle

© 2020 Dr. Ashraf Armoush , An-Najah National University 16


Point and Circle Test
public class Test {
// test when constructors and finalizers are called
public static void main( String args[] )
{ Point P = new Point();
Circle circle1, circle2;
circle1 = new Circle( 4.5, 72, 29 );
circle2 = new Circle( 10, 5, 5 );
P = null; // mark for garbage collection
circle1 = null; // mark for garbage collection
circle2 = null; // mark for garbage collection
System.gc(); // call the garbage collector
}
Point constructor: [0, 0]
} // end class Test Point constructor: Center = [72, 29]; Radius = 0.0
Circle constructor: Center = [72, 29]; Radius = 4.5
Point constructor: Center = [5, 5]; Radius = 0.0
Circle constructor: Center = [5, 5]; Radius = 10.0
Circle finalizer: Center = [5, 5]; Radius = 10.0
Circle finalizer: Center = [72, 29]; Radius = 4.5
Point finalizer: [0, 0]

© 2020 Dr. Ashraf Armoush , An-Najah National University 17

• The finalize() method may be called


automatically by the system, but when it is
called, or even if it is called, is uncertain.
– Therefore, you should not rely on this method to
do your cleanup for you.

– finalize() is not automatically called for


the super class
• Use super.finalize() to explicitly call the
original version from the super class.

© 2020 Dr. Ashraf Armoush , An-Najah National University 18


Class Object
• All classes in Java inherit directly or indirectly from the Object
class (package java.lang),
• So, its 11 methods are inherited by all other classes.
Method Summary
clone( )
Creates and returns a copy of this object.
equals(Object obj)
Indicates whether some other object is "equal to" this one.
finalize()
Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
getClass()
Returns the runtime class of this Object.
hashCode()
Returns a hash code value for the object.
toString()
Returns a string representation of the object.
© 2020 Dr. Ashraf Armoush , An-Najah National University 19

Class Object (cont.)


notify()
Wakes up a single thread that is waiting on this object's monitor.
notifyAll()
Wakes up all threads that are waiting on this object's monitor.

wait()
Causes the current thread to wait until another thread invokes the notify() method
or the notifyAll() method for this object.
wait(long timeout)
Causes the current thread to wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
wait(long timeout, int nanos)
Causes the current thread to wait until another thread invokes the notify() method
or the notifyAll() method for this object, or some other thread interrupts the current
thread, or a certain amount of real time has elapsed.

© 2020 Dr. Ashraf Armoush , An-Najah National University 20


Example: Person and its subclasses

© 2020 Dr. Ashraf Armoush , An-Najah National University 21

Example: Person and its subclasses (cont.)


public class Person {
// Instance variables
private String name;
private String address;

// Constructor
public Person(String name, String address) {
this.name = name;
this.address = address;
}

// Getters
public String getName() {
return name;
}
public String getAddress() {
return address;
}

public String toString() {


return name + "(" + address + ")";
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 22


Example: Person and its subclasses (cont.)
public class Student extends Person {
// Instance variables
private int numCourses; // number of courses taken so far, max 30
private String[] courses; // course codes
private int[] grades; // grade for the corresponding course codes
private static final int MAX_COURSES = 30; // maximum number of courses
// Constructor
public Student(String name, String address) {
super(name, address);
numCourses = 0;
courses = new String[MAX_COURSES];
grades = new int[MAX_COURSES];
}

@Override
public String toString() {
return "Student: " + super.toString();
}

// Add a course and its grade - No validation in this method


public void addCourseGrade(String course, int grade) {
courses[numCourses] = course;
grades[numCourses] = grade;
++numCourses;
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 23

Example: Person and its subclasses (cont.)


// Print all courses taken and their grade
public void printGrades() {
System.out.print(this);
for (int i = 0; i < numCourses; ++i) {
System.out.print(" " + courses[i] + ":" + grades[i]);
}
System.out.println();
}

// Compute the average grade


public double getAverageGrade() {
int sum = 0;
for (int i = 0; i < numCourses; i++ ) {
sum += grades[i];
}
return (double)sum/numCourses;
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 24


Example: Person and its subclasses (cont.)
public class Teacher extends Person {
// Instance variables
private int numCourses; // number of courses taught currently
private String[] courses; // course codes
private static final int MAX_COURSES = 10; // maximum courses
// Constructor
public Teacher(String name, String address) {
super(name, address);
numCourses = 0;
courses = new String[MAX_COURSES];
}
@Override
public String toString() {
return "Teacher: " + super.toString();
}

// Return false if duplicate course to be added


public boolean addCourse(String course) {
// Check if the course already in the course list
for (int i = 0; i < numCourses; i++) {
if (courses[i].equals(course)) return false;
}
courses[numCourses] = course;
numCourses++;
return true;
}
© 2020 Dr. Ashraf Armoush , An-Najah National University 25

Example: Person and its subclasses (cont.)


// Return false if the course does not in the course list
public boolean removeCourse(String course) {
// Look for the course index
int courseIndex = numCourses;
for (int i = 0; i < numCourses; i++) {
if (courses[i].equals(course)) {
courseIndex = i;
break;
}
}
if (courseIndex == numCourses) { // cannot find the course to be
removed
return false;
} else { // remove the course and re-arrange for courses array
for (int i = courseIndex; i < numCourses-1; i++) {
courses[i] = courses[i+1];
}
numCourses--;
return true;
}
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 26


Example: Person and its subclasses (cont.)
// A test driver program for Person and its subclasses

public class Test {

public static void main(String[] args) {

// Test Student class


Student s1 = new Student("Ali", "Nablus");
s1.addCourseGrade("Math101", 97);
s1.addCourseGrade("Math102", 68);
s1.printGrades();

System.out.println("Average is " + s1.getAverageGrade());

// Test Teacher class


Teacher t1 = new Teacher("Ahmad", "Ramallah");
System.out.println(t1);
String[] courses = {"Math101", "Math102", "Math101"};
for (String course: courses) {
if (t1.addCourse(course)) {
System.out.println(course + " added.");
} else {
System.out.println(course + " cannot be added.");
}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 27

Example: Person and its subclasses (cont.)


for (String course: courses) {
if (t1.removeCourse(course)) {
System.out.println(course + " removed.");
} else {
System.out.println(course + " cannot be removed.");
}
}
}
}

Student: Ali(Nablus) Math101:97 Math102:68


Average is 82.5
Teacher: Ahmad(Ramallah)
Math101 added.
Math102 added.
Math101 cannot be added.
Math101 removed.
Math102 removed.
Math101 cannot be removed.

© 2020 Dr. Ashraf Armoush , An-Najah National University 28


Annotation
• Annotations:
– a form of metadata (provide data about a program that is
not part of the program itself.)
– have no direct effect on the operation of the code they
annotate.
– became available in JDK 1.5

• Annotations have a number of uses, among them:


– Information for the compiler — Annotations can be used
by the compiler to detect errors or suppress warnings.
– Compile-time and deployment-time processing —
Software tools can process annotation information to
generate code, XML files, and so forth.
– Runtime processing — Some annotations are available to
be examined at runtime.

© 2020 Dr. Ashraf Armoush , An-Najah National University 29

Annotation - @
• Annotation:
– a form of metadata (provide data about a program that is
not part of the program itself.)
– have no direct effect on the operation of the code they
annotate.
– became available in JDK 1.5

• Annotations have a number of uses, among them:


– Information for the compiler — Annotations can be used
by the compiler to detect errors or suppress warnings.
– Compile-time and deployment-time processing —
Software tools can process annotation information to
generate code, XML files, and so forth.
– Runtime processing — Some annotations are available to
be examined at runtime.

© 2020 Dr. Ashraf Armoush , An-Najah National University 30


Annotation (cont.)
• @Deprecated
– annotation indicates that the marked element is deprecated and
should no longer be used.

– The compiler generates a warning whenever a program


uses a method, class, or field with the @Deprecated
annotation.
• @Override
• @SuppressWarnings
• @SafeVarargs
• @FunctionalInterface
© 2020 Dr. Ashraf Armoush , An-Najah National University 31

@override annotation
• @override: Checks that the method is an override.
– Informs the compiler that the element is meant to
override an element declared in a superclass

– Causes a compile error if the method is not found in one of


the parent classes or implemented interfaces
public String toString() { //override method

public String toSTring() { //new method

@Override
public String toSTring() { //create a compile error

© 2020 Dr. Ashraf Armoush , An-Najah National University 32


Inheritance vs. Composition
• Inheritance and composition are two mechanisms for
achieving code reuse
• “is-a” vs. “has-a”
– “is-a”
• Inheritance
• subclass object treated as superclass object
• Example: Car is a vehicle
– Vehicle properties/behaviors also car properties/behaviors
– “has-a”
• Composition (Aggregation)
• Object contains one or more objects of other classes as
members
• Example: Car has a steering wheel/ Car has an Engine

© 2020 Dr. Ashraf Armoush , An-Najah National University 33

Inheritance vs. Composition (cont.)

class Engine {
..
}

class Vehicle {
..
}

class Car extends Vehicle {


Engine engine;

}
© 2020 Dr. Ashraf Armoush , An-Najah National University 34
Inheritance vs. Composition (cont.)
• Which works best, composition or inheritance
in each of the following situations?

– Student / Professor /TeachingAssistant /Employee


/Secretary /DepartmentChair /Person

– Library/Book/chapter

– Department/Employee

– Circle/Point ???
© 2020 Dr. Ashraf Armoush , An-Najah National University 35

You might also like