CS111: PROGRAMMING LANGUAGE II · OOP - Inheritance Inheritance represents the is a relationship...
Transcript of CS111: PROGRAMMING LANGUAGE II · OOP - Inheritance Inheritance represents the is a relationship...
CS111: PROGRAMMING
LANGUAGE II
Lecture 4(a): Introduction to Inheritance Computer Science
Department
Lecture Contents
Dr. Amal Khalifa, 2014
What is Inheritance?
Super-class & sub class
The object class
Using extends keyword
@override keyword
OOP
Dr. Amal Khalifa, 2014
OOP - Inheritance
A class can extend another class, inheriting all its data
members and methods while redefining some of them
and/or adding its own.
Dr. Amal Khalifa, 2014
OOP - Inheritance
Inheritance represents the is a relationship between
data types (e.g. student/person)
Existing class is the superclass (more general)
New class is the subclass (more specific)
Java supports only single inheritance
each class is derived from exactly one direct
superclass.
Possible to Create hierarchy of classes
Dr. Amal Khalifa, 2014
Superclasses and Subclasses
Superclasses
“more
general”
subclasses
“more
specific.”
every
subclass
object is an
object of its
superclass
Dr. Amal Khalifa, 2014
The Object Class
Dr. Amal Khalifa, 2014
The Java class hierarchy begins with class Object
(in package java.lang)
Every class in Java directly or indirectly extends (or
“inherits from”) Object.
All classes in Java inherit directly or indirectly from
Object, so its 11 methods are inherited by all other
classes.
The Object Class
Dr. Amal Khalifa, 2014
The Object Class
Dr. Amal Khalifa, 2014
The Object Class
learn more about Object’s methods at: java.sun.com/javase-6/docs/api/java/lang/Object.html Or java.sun.com/docs/books/tutorial/java/IandI/ objectclass.html
Apply on Student class
Dr. Amal Khalifa, 2014
Does your class extends Object?
If you don’t explicitly specify which class a new class extends, the class extends Object implicitly.
What methods did you redefine (override)?
finalize()
toString()
equals()
To override a superclass method, a subclass must declare a method with the same signature as the superclass method or a compilation error occurs
@Override annotation
Programming Pitfalls!!
Dr. Amal Khalifa, 2014
Superclasses and Subclasses
Dr. Amal Khalifa, 2014
Inheritance issue
A subclass can inherit methods that it does not need or
should not have.
Even when a superclass method is appropriate for a
subclass, that subclass often needs a customized
version of the method.
The subclass can override (redefine) the superclass
method with an appropriate implementation.
An overrided subclass method can access the superclass method
using the keyword super and a dot (.) separator.
Book Ref.
working on Chap. 9
That’s all for today…..
Dr. Amal Khalifa, 2014