SlideShare une entreprise Scribd logo
1  sur  40
Object Oriented Programming
Chapter 3: Inheritance
Prepared by: Mahmoud Rafeek Alfarra
2016
‫تعاىل‬ ‫اهلل‬ ‫قال‬:
(‫َلَى‬‫ع‬ ‫ُوا‬‫ف‬َ‫ر‬ ْ‫س‬ َ‫أ‬ َ‫ن‬‫ِي‬‫ذ‬َّ‫ل‬‫ا‬ َ‫ي‬ِ‫د‬‫ِبَا‬‫ع‬ ‫يَا‬ ْ‫ل‬ُ‫ق‬
َّ‫ِن‬‫إ‬ ِ‫ه‬َّ‫ل‬‫ال‬ ِ‫ة‬َ‫م‬ْ‫ح‬َّ‫ر‬ ‫ِن‬‫م‬ ‫ُوا‬‫ط‬َ‫ن‬ْ‫ق‬َ‫ت‬ ‫َا‬‫ل‬ ْ‫م‬ِ‫ه‬ِ‫س‬ُ‫ف‬‫َن‬‫أ‬
َ‫و‬ُ‫ه‬ ُ‫ه‬َّ‫ِن‬‫إ‬ ‫ِيعًا‬‫م‬َ‫ج‬ َ‫ب‬‫ُو‬‫ن‬ُّ‫لذ‬ ‫ا‬ ُ‫ر‬ِ‫ْف‬‫غ‬َ‫ي‬ َ‫ه‬َّ‫الل‬
ُ‫م‬‫ِي‬‫ح‬َّ‫ر‬‫ال‬ ُ‫ر‬‫ُو‬‫ف‬َ‫غ‬ْ‫ل‬‫ا‬)
Outlines
◉ Motivation
◉ What is Inheritance ?
◉ Types of Inheritance
◉ Superclasses and Subclasses
◉ Defining a Subclass
◉ "is-a" and the "has-a" relationship
Note: I have prepared this material Based on (Liang: “Introduction to Programming using Java”, 10’th edition, 2015)
◉ Are superclass’s Constructor Inherited?
◉ Overriding Methods in the Subclass
◉ Full Example
◉ Important Notes
Lecture
Let’s think on Inheritance
1
o Suppose you will define classes to model circles, rectangles, and
triangles.
o These classes have many common features. What is the best way
to design these classes so to avoid redundancy?
The answer is to use inheritance.
Motivation
What is Inheritance ?
o Inheritance is a form of software reuse in which a new class is
created by absorbing an existing class's members and
embellishing them with new or modified capabilities.
P_Properties
P_ methods
Parent Class
C_Properties
C_methods
Child Class
This class has its
properties, methods
and that of its parent.
Types of Inheritance
Single Inheritance
When a Derived Class to
inherit properties and
behavior from a single Base
Class, it is called as single
inheritance.
Multi Level Inheritance
A derived class is created
from another derived class
is called Multi Level
Inheritance.
Hierarchical Inheritance
More than one derived class
are created from a single
base class, is called
Hierarchical Inheritance
Types of Inheritance
Hybrid Inheritance
Any combination of above
three inheritance (single,
hierarchical and multi level) is
called as hybrid inheritance.
Multiple Inheritance
Multiple inheritances allows
programmers to create classes
that combine aspects of
multiple classes and their
corresponding hierarchies.
Superclasses and
Subclasses
GeometricObject
-color: String
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
+GeometricObject(color: String,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
The color of the object (default: white).
Indicates whether the object is filled with a color (default: false).
The date when the object was created.
Creates a GeometricObject.
Creates a GeometricObject with the specified color and filled
values.
Returns the color.
Sets a new color.
Returns the filled property.
Sets a new filled property.
Returns the dateCreated.
Returns a string representation of this object.
Circle
-radius: double
+Circle()
+Circle(radius: double)
+Circle(radius: double, color: String,
filled: boolean)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
+printCircle(): void
Rectangle
-width: double
-height: double
+Rectangle()
+Rectangle(width: double, height: double)
+Rectangle(width: double, height: double
color: String, filled: boolean)
+getWidth(): double
+setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
+getArea(): double
+getPerimeter(): double
o In Java, as in other object-oriented programming languages,
classes can be derived from other classes.
o The derived class (the class that is derived from another class)
is called a subclass.
o The class from which its derived is called the superclass.
Superclasses and Subclasses
o A subclass normally adds its own fields and methods.
o Therefore, a subclass is more specific than its superclass.
o Typically, the subclass exhibits the behaviors of its superclass
and additional behaviors that are specific to the subclass.
Superclasses and Subclasses
Direct & Indirect Superclasses
properties3
methods3 SubClass
properties1
methods1
Indirect
SuperClass
properties2
methods2 Direct
SuperClass
o The direct superclass is the superclass
from which the subclass explicitly
inherits.
o An indirect superclass is any class above
the direct superclass in the class
hierarchy.
o A subclass inherits from a superclass. You can also:
 Add new properties
 Add new methods
 Override the methods of the superclass.
Defining a Subclass
Defining a Subclass
public class Faculty extends Employee {
//…
}
SubClass SuperClass
Defining a Subclass
class Vehicle {
protected String model;
protected float price;
public Vehicle(String model, float price){
this.model = model;
this.price = price;
}
public String print(){
return "Model: "+model+"t Price: "+price;
}
public void setModel(String model){
this.model = model;
}
public String getModel(){
return model;
} // set and get of price
}
Vehicle
Class SuperClass
Car Class SubClass
Defining a Subclass
class Car extends Vehicle{
private int passengers;
public Car(String model, float price,int passengers){
super( model, price);
this.passengers = passengers;
}
public String print(){
return "Data is:n"+super.print()+
" # of passengers: "+passengers;
}
}
Defining a Subclass
public class VehicleProjectInheritance {
public static void main(String[] args) {
Car c = new Car("Honda", 455.0f, 4);
System.out.println(c.print());
}
}
"is-a" and the "has-a" relationship
o "Is-a" represents inheritance.
o In an "is-a" relationship, an object of a subclass can also be
treated as an object of its superclass.
o “Has–a” represents the encapsulation, i.e: The relation between
object and its members.
"is-a" and the "has-a" relationship
Vehicle
Class SuperClass
Car Class SubClass
Honda is a car &
Honda is a vehicle
Object of sub is also an object of super
THANKS!
Any questions?
You can find me at:
Fb/mahmoudRAlfarra
Staff.cst.ps/mfarra
Youtube.com/mralfarra1
@mralfarra
‫تعاىل‬ ‫اهلل‬ ‫قال‬:
(‫باده‬‫ع‬ ‫عن‬ ‫بة‬‫التو‬ ‫بل‬‫يق‬ ‫لذي‬‫ا‬ ‫هو‬‫و‬
‫السيئات‬ ‫عن‬ ‫ويعفو‬)
Lecture
Let’s focus on Superclass’s Constructor
2
Are superclass’s Constructor Inherited?
o No. They are not inherited.
o They are invoked explicitly or implicitly.
o Explicitly using the super keyword.
o A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's constructors are
not inherited in the subclass.
Superclass’s Constructor Is Always Invoked
o A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked explicitly,
the compiler puts super() as the first statement in the
constructor. For example,
public A(double d) {
// some statements
}
is equivalent to
public A(double d) {
super();
// some statements
}
public A() {
}
is equivalent to
public A() {
super();
}
Using the Keyword super
o The keyword super refers to the superclass of the class in
which super appears. This keyword can be used in two ways:
1. To call a superclass constructor
2. To call a superclass method
Constructor Chaining
o Constructing an instance of a class invokes all the superclasses’
constructors along the inheritance chain.
o This is known as constructor chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
Overriding Methods in the Subclass
o A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a
method defined in the superclass.
o This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in GeometricObject */
public String toString() {
return super.toString() + "nradius is " + radius; }
}
Overriding vs. Overloading
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overrides the method in B
public void p(double i) {
System.out.println(i);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overloads the method in B
public void p(int i) {
System.out.println(i);
}
}
Overriding vs. Overloading
o The example above show the differences between overriding
and overloading.
o In (a), the method p(double i) in class A overrides the same
method in class B.
o In (b), the class A has two overloaded methods: p(double i) and
p(int i).
o The method p(double i) is inherited from B.
Full Example
Student
Post
Graduate
Graduate
• Have part time hours • Have a field training
Full Example
o Constructing an instance of a class invokes all the superclasses’
constructors along the inheritance chain.
o This is known as constructor chaining.
Full Example
Methods of a subclass cannot directly access private members of their
superclass.
With inheritance, the common instance variables and methods of all the
classes in the hierarchy are declared in a superclass.
Use the protected access modifier when a superclass should
provide a method only to its subclasses and other classes in
the same package, but not to other clients.
Full Example
A subclass is more specific than its superclass and represents a smaller
group of objects.
A superclass's protected members have an intermediate level
of protection between public and private access. They can be
accessed by members of the superclass, by members of its
subclasses and by members of other classes in the same
package.
A compilation error occurs if a subclass constructor calls one
of its superclass constructors with arguments that do not match
the superclass constructor declarations.
Full Example
In Java, the class hierarchy begins with class Object (in package
java.lang), which every class in Java directly or indirectly extends.
Invoking a superclass constructor’s name in a subclass causes a syntax
error.
Java requires that the statement that uses the keyword super appear first
in the constructor.
If a class is designed to be extended, it is better to provide a no-arg
constructor to avoid programming errors.
Practices
Practice 1
Using charts, What is
Inheritance ?
Practice 2
Compare between the
Types of Inheritance
and which of them
supported in java.
Practice 3
By UML class, explain
the concepts of
Superclasses and
Subclasses.
Practice 4
Give 3 examples to
explain Direct & Indirect
Superclasses.
Practice 5
Diffrenciate between
"is-a" and the "has-
a" relationship.
Practice 6
Explain the
Constructor Chaining
using code.
Practices
Practice 7
True or false?
 You can override a
private method
defined in a
superclass.
 You can override a
static method
defined in a
superclass.
 A subclass is a
subset of a
superclass.
Practice 8
Write simple code:
 What keyword do
you use to define a
subclass?
 How do you
explicitly invoke a
superclass’s
constructor from a
subclass?
 How do you invoke
an overridden
superclass method
from a subclass?
Practice 9 (In groups)
Define The
GeometricObject,
Circle and Rectangle,
based on the
GeometricObject is the
superclass for Circle
Rectangle .
THANKS!
Any questions?
You can find me at:
Fb/mahmoudRAlfarra
Staff.cst.ps/mfarra
Youtube.com/mralfarra1
@mralfarra

Contenu connexe

Tendances

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
البرمجة الهدفية بلغة جافا - مصفوفة الكائنات
البرمجة الهدفية  بلغة جافا - مصفوفة الكائناتالبرمجة الهدفية  بلغة جافا - مصفوفة الكائنات
البرمجة الهدفية بلغة جافا - مصفوفة الكائناتMahmoud Alfarra
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objectsMahmoud Alfarra
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism JavaM. Raihan
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and objectFajar Baskoro
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 

Tendances (20)

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
البرمجة الهدفية بلغة جافا - مصفوفة الكائنات
البرمجة الهدفية  بلغة جافا - مصفوفة الكائناتالبرمجة الهدفية  بلغة جافا - مصفوفة الكائنات
البرمجة الهدفية بلغة جافا - مصفوفة الكائنات
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objects
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Java unit2
Java unit2Java unit2
Java unit2
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Inheritance
InheritanceInheritance
Inheritance
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Class and object
Class and objectClass and object
Class and object
 

En vedette

15 نصيحة للطالب الجامعي الجديد
15 نصيحة للطالب الجامعي الجديد15 نصيحة للطالب الجامعي الجديد
15 نصيحة للطالب الجامعي الجديدMahmoud Alfarra
 
graph based cluster labeling using GHSOM
graph based cluster labeling using GHSOMgraph based cluster labeling using GHSOM
graph based cluster labeling using GHSOMMahmoud Alfarra
 
ثلاث خطوات عملية للطالب الجامعي قبل الامتحان
ثلاث خطوات عملية للطالب الجامعي قبل الامتحانثلاث خطوات عملية للطالب الجامعي قبل الامتحان
ثلاث خطوات عملية للطالب الجامعي قبل الامتحانMahmoud Alfarra
 
linked list
linked listlinked list
linked listAbbott
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1Kumar
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
البرمجة الهدفية بلغة جافا - مقدمة
البرمجة الهدفية بلغة جافا - مقدمةالبرمجة الهدفية بلغة جافا - مقدمة
البرمجة الهدفية بلغة جافا - مقدمةMahmoud Alfarra
 
5 Array List, data structure course
5 Array List, data structure course5 Array List, data structure course
5 Array List, data structure courseMahmoud Alfarra
 
Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)Adam Mukharil Bachtiar
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureRai University
 
Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1Mahmoud Alfarra
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Hassan Ahmed
 

En vedette (20)

Graphs data Structure
Graphs data StructureGraphs data Structure
Graphs data Structure
 
15 نصيحة للطالب الجامعي الجديد
15 نصيحة للطالب الجامعي الجديد15 نصيحة للطالب الجامعي الجديد
15 نصيحة للطالب الجامعي الجديد
 
graph based cluster labeling using GHSOM
graph based cluster labeling using GHSOMgraph based cluster labeling using GHSOM
graph based cluster labeling using GHSOM
 
ثلاث خطوات عملية للطالب الجامعي قبل الامتحان
ثلاث خطوات عملية للطالب الجامعي قبل الامتحانثلاث خطوات عملية للطالب الجامعي قبل الامتحان
ثلاث خطوات عملية للطالب الجامعي قبل الامتحان
 
01 05 - introduction xml
01  05 - introduction xml01  05 - introduction xml
01 05 - introduction xml
 
linked list
linked listlinked list
linked list
 
L6 structure
L6 structureL6 structure
L6 structure
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
البرمجة الهدفية بلغة جافا - مقدمة
البرمجة الهدفية بلغة جافا - مقدمةالبرمجة الهدفية بلغة جافا - مقدمة
البرمجة الهدفية بلغة جافا - مقدمة
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
5 Array List, data structure course
5 Array List, data structure course5 Array List, data structure course
5 Array List, data structure course
 
3 Array operations
3   Array operations3   Array operations
3 Array operations
 
Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)
 
Data structures
Data structuresData structures
Data structures
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1Object Oriented Programming in Java _lecture 1
Object Oriented Programming in Java _lecture 1
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...Data structure,abstraction,abstract data type,static and dynamic,time and spa...
Data structure,abstraction,abstract data type,static and dynamic,time and spa...
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 

Similaire à ‫Chapter3 inheritance

Similaire à ‫Chapter3 inheritance (20)

java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
11slide
11slide11slide
11slide
 
Inheritance
InheritanceInheritance
Inheritance
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Inheritance
InheritanceInheritance
Inheritance
 
Java
JavaJava
Java
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
Core java oop
Core java oopCore java oop
Core java oop
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Uta005
Uta005Uta005
Uta005
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – II  NOTES FINAL.pdfCS3391 -OOP -UNIT – II  NOTES FINAL.pdf
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
A457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.pptA457405934_21789_26_2018_Inheritance.ppt
A457405934_21789_26_2018_Inheritance.ppt
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritance
 

Plus de Mahmoud Alfarra

Computer Programming, Loops using Java - part 2
Computer Programming, Loops using Java - part 2Computer Programming, Loops using Java - part 2
Computer Programming, Loops using Java - part 2Mahmoud Alfarra
 
Computer Programming, Loops using Java
Computer Programming, Loops using JavaComputer Programming, Loops using Java
Computer Programming, Loops using JavaMahmoud Alfarra
 
Chapter 10: hashing data structure
Chapter 10:  hashing data structureChapter 10:  hashing data structure
Chapter 10: hashing data structureMahmoud Alfarra
 
Chapter9 graph data structure
Chapter9  graph data structureChapter9  graph data structure
Chapter9 graph data structureMahmoud Alfarra
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structureMahmoud Alfarra
 
Chapter 7: Queue data structure
Chapter 7:  Queue data structureChapter 7:  Queue data structure
Chapter 7: Queue data structureMahmoud Alfarra
 
Chapter 6: stack data structure
Chapter 6:  stack data structureChapter 6:  stack data structure
Chapter 6: stack data structureMahmoud Alfarra
 
Chapter 5: linked list data structure
Chapter 5: linked list data structureChapter 5: linked list data structure
Chapter 5: linked list data structureMahmoud Alfarra
 
Chapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structureChapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structureMahmoud Alfarra
 
Chapter 3: basic sorting algorithms data structure
Chapter 3: basic sorting algorithms data structureChapter 3: basic sorting algorithms data structure
Chapter 3: basic sorting algorithms data structureMahmoud Alfarra
 
Chapter 2: array and array list data structure
Chapter 2: array and array list  data structureChapter 2: array and array list  data structure
Chapter 2: array and array list data structureMahmoud Alfarra
 
Chapter1 intro toprincipleofc#_datastructure_b_cs
Chapter1  intro toprincipleofc#_datastructure_b_csChapter1  intro toprincipleofc#_datastructure_b_cs
Chapter1 intro toprincipleofc#_datastructure_b_csMahmoud Alfarra
 
Chapter 0: introduction to data structure
Chapter 0: introduction to data structureChapter 0: introduction to data structure
Chapter 0: introduction to data structureMahmoud Alfarra
 
8 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 201020118 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 20102011Mahmoud Alfarra
 
7 programming-using-java decision-making220102011
7 programming-using-java decision-making2201020117 programming-using-java decision-making220102011
7 programming-using-java decision-making220102011Mahmoud Alfarra
 
6 programming-using-java decision-making20102011-
6 programming-using-java decision-making20102011-6 programming-using-java decision-making20102011-
6 programming-using-java decision-making20102011-Mahmoud Alfarra
 
5 programming-using-java intro-tooop20102011
5 programming-using-java intro-tooop201020115 programming-using-java intro-tooop20102011
5 programming-using-java intro-tooop20102011Mahmoud Alfarra
 
4 programming-using-java intro-tojava20102011
4 programming-using-java intro-tojava201020114 programming-using-java intro-tojava20102011
4 programming-using-java intro-tojava20102011Mahmoud Alfarra
 
3 programming-using-java introduction-to computer
3 programming-using-java introduction-to computer3 programming-using-java introduction-to computer
3 programming-using-java introduction-to computerMahmoud Alfarra
 

Plus de Mahmoud Alfarra (20)

Computer Programming, Loops using Java - part 2
Computer Programming, Loops using Java - part 2Computer Programming, Loops using Java - part 2
Computer Programming, Loops using Java - part 2
 
Computer Programming, Loops using Java
Computer Programming, Loops using JavaComputer Programming, Loops using Java
Computer Programming, Loops using Java
 
Chapter 10: hashing data structure
Chapter 10:  hashing data structureChapter 10:  hashing data structure
Chapter 10: hashing data structure
 
Chapter9 graph data structure
Chapter9  graph data structureChapter9  graph data structure
Chapter9 graph data structure
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structure
 
Chapter 7: Queue data structure
Chapter 7:  Queue data structureChapter 7:  Queue data structure
Chapter 7: Queue data structure
 
Chapter 6: stack data structure
Chapter 6:  stack data structureChapter 6:  stack data structure
Chapter 6: stack data structure
 
Chapter 5: linked list data structure
Chapter 5: linked list data structureChapter 5: linked list data structure
Chapter 5: linked list data structure
 
Chapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structureChapter 4: basic search algorithms data structure
Chapter 4: basic search algorithms data structure
 
Chapter 3: basic sorting algorithms data structure
Chapter 3: basic sorting algorithms data structureChapter 3: basic sorting algorithms data structure
Chapter 3: basic sorting algorithms data structure
 
Chapter 2: array and array list data structure
Chapter 2: array and array list  data structureChapter 2: array and array list  data structure
Chapter 2: array and array list data structure
 
Chapter1 intro toprincipleofc#_datastructure_b_cs
Chapter1  intro toprincipleofc#_datastructure_b_csChapter1  intro toprincipleofc#_datastructure_b_cs
Chapter1 intro toprincipleofc#_datastructure_b_cs
 
Chapter 0: introduction to data structure
Chapter 0: introduction to data structureChapter 0: introduction to data structure
Chapter 0: introduction to data structure
 
3 classification
3  classification3  classification
3 classification
 
8 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 201020118 programming-using-java decision-making practices 20102011
8 programming-using-java decision-making practices 20102011
 
7 programming-using-java decision-making220102011
7 programming-using-java decision-making2201020117 programming-using-java decision-making220102011
7 programming-using-java decision-making220102011
 
6 programming-using-java decision-making20102011-
6 programming-using-java decision-making20102011-6 programming-using-java decision-making20102011-
6 programming-using-java decision-making20102011-
 
5 programming-using-java intro-tooop20102011
5 programming-using-java intro-tooop201020115 programming-using-java intro-tooop20102011
5 programming-using-java intro-tooop20102011
 
4 programming-using-java intro-tojava20102011
4 programming-using-java intro-tojava201020114 programming-using-java intro-tojava20102011
4 programming-using-java intro-tojava20102011
 
3 programming-using-java introduction-to computer
3 programming-using-java introduction-to computer3 programming-using-java introduction-to computer
3 programming-using-java introduction-to computer
 

Dernier

80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Dernier (20)

80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

‫Chapter3 inheritance

  • 1. Object Oriented Programming Chapter 3: Inheritance Prepared by: Mahmoud Rafeek Alfarra 2016
  • 2. ‫تعاىل‬ ‫اهلل‬ ‫قال‬: (‫َلَى‬‫ع‬ ‫ُوا‬‫ف‬َ‫ر‬ ْ‫س‬ َ‫أ‬ َ‫ن‬‫ِي‬‫ذ‬َّ‫ل‬‫ا‬ َ‫ي‬ِ‫د‬‫ِبَا‬‫ع‬ ‫يَا‬ ْ‫ل‬ُ‫ق‬ َّ‫ِن‬‫إ‬ ِ‫ه‬َّ‫ل‬‫ال‬ ِ‫ة‬َ‫م‬ْ‫ح‬َّ‫ر‬ ‫ِن‬‫م‬ ‫ُوا‬‫ط‬َ‫ن‬ْ‫ق‬َ‫ت‬ ‫َا‬‫ل‬ ْ‫م‬ِ‫ه‬ِ‫س‬ُ‫ف‬‫َن‬‫أ‬ َ‫و‬ُ‫ه‬ ُ‫ه‬َّ‫ِن‬‫إ‬ ‫ِيعًا‬‫م‬َ‫ج‬ َ‫ب‬‫ُو‬‫ن‬ُّ‫لذ‬ ‫ا‬ ُ‫ر‬ِ‫ْف‬‫غ‬َ‫ي‬ َ‫ه‬َّ‫الل‬ ُ‫م‬‫ِي‬‫ح‬َّ‫ر‬‫ال‬ ُ‫ر‬‫ُو‬‫ف‬َ‫غ‬ْ‫ل‬‫ا‬)
  • 3.
  • 4. Outlines ◉ Motivation ◉ What is Inheritance ? ◉ Types of Inheritance ◉ Superclasses and Subclasses ◉ Defining a Subclass ◉ "is-a" and the "has-a" relationship Note: I have prepared this material Based on (Liang: “Introduction to Programming using Java”, 10’th edition, 2015) ◉ Are superclass’s Constructor Inherited? ◉ Overriding Methods in the Subclass ◉ Full Example ◉ Important Notes
  • 5. Lecture Let’s think on Inheritance 1
  • 6. o Suppose you will define classes to model circles, rectangles, and triangles. o These classes have many common features. What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance. Motivation
  • 7. What is Inheritance ? o Inheritance is a form of software reuse in which a new class is created by absorbing an existing class's members and embellishing them with new or modified capabilities. P_Properties P_ methods Parent Class C_Properties C_methods Child Class This class has its properties, methods and that of its parent.
  • 8. Types of Inheritance Single Inheritance When a Derived Class to inherit properties and behavior from a single Base Class, it is called as single inheritance. Multi Level Inheritance A derived class is created from another derived class is called Multi Level Inheritance. Hierarchical Inheritance More than one derived class are created from a single base class, is called Hierarchical Inheritance
  • 9. Types of Inheritance Hybrid Inheritance Any combination of above three inheritance (single, hierarchical and multi level) is called as hybrid inheritance. Multiple Inheritance Multiple inheritances allows programmers to create classes that combine aspects of multiple classes and their corresponding hierarchies.
  • 10. Superclasses and Subclasses GeometricObject -color: String -filled: boolean -dateCreated: java.util.Date +GeometricObject() +GeometricObject(color: String, filled: boolean) +getColor(): String +setColor(color: String): void +isFilled(): boolean +setFilled(filled: boolean): void +getDateCreated(): java.util.Date +toString(): String The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created. Creates a GeometricObject. Creates a GeometricObject with the specified color and filled values. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the dateCreated. Returns a string representation of this object. Circle -radius: double +Circle() +Circle(radius: double) +Circle(radius: double, color: String, filled: boolean) +getRadius(): double +setRadius(radius: double): void +getArea(): double +getPerimeter(): double +getDiameter(): double +printCircle(): void Rectangle -width: double -height: double +Rectangle() +Rectangle(width: double, height: double) +Rectangle(width: double, height: double color: String, filled: boolean) +getWidth(): double +setWidth(width: double): void +getHeight(): double +setHeight(height: double): void +getArea(): double +getPerimeter(): double
  • 11. o In Java, as in other object-oriented programming languages, classes can be derived from other classes. o The derived class (the class that is derived from another class) is called a subclass. o The class from which its derived is called the superclass. Superclasses and Subclasses
  • 12. o A subclass normally adds its own fields and methods. o Therefore, a subclass is more specific than its superclass. o Typically, the subclass exhibits the behaviors of its superclass and additional behaviors that are specific to the subclass. Superclasses and Subclasses
  • 13. Direct & Indirect Superclasses properties3 methods3 SubClass properties1 methods1 Indirect SuperClass properties2 methods2 Direct SuperClass o The direct superclass is the superclass from which the subclass explicitly inherits. o An indirect superclass is any class above the direct superclass in the class hierarchy.
  • 14. o A subclass inherits from a superclass. You can also:  Add new properties  Add new methods  Override the methods of the superclass. Defining a Subclass
  • 15. Defining a Subclass public class Faculty extends Employee { //… } SubClass SuperClass
  • 16. Defining a Subclass class Vehicle { protected String model; protected float price; public Vehicle(String model, float price){ this.model = model; this.price = price; } public String print(){ return "Model: "+model+"t Price: "+price; } public void setModel(String model){ this.model = model; } public String getModel(){ return model; } // set and get of price } Vehicle Class SuperClass Car Class SubClass
  • 17. Defining a Subclass class Car extends Vehicle{ private int passengers; public Car(String model, float price,int passengers){ super( model, price); this.passengers = passengers; } public String print(){ return "Data is:n"+super.print()+ " # of passengers: "+passengers; } }
  • 18. Defining a Subclass public class VehicleProjectInheritance { public static void main(String[] args) { Car c = new Car("Honda", 455.0f, 4); System.out.println(c.print()); } }
  • 19. "is-a" and the "has-a" relationship o "Is-a" represents inheritance. o In an "is-a" relationship, an object of a subclass can also be treated as an object of its superclass. o “Has–a” represents the encapsulation, i.e: The relation between object and its members.
  • 20. "is-a" and the "has-a" relationship Vehicle Class SuperClass Car Class SubClass Honda is a car & Honda is a vehicle Object of sub is also an object of super
  • 21. THANKS! Any questions? You can find me at: Fb/mahmoudRAlfarra Staff.cst.ps/mfarra Youtube.com/mralfarra1 @mralfarra
  • 22. ‫تعاىل‬ ‫اهلل‬ ‫قال‬: (‫باده‬‫ع‬ ‫عن‬ ‫بة‬‫التو‬ ‫بل‬‫يق‬ ‫لذي‬‫ا‬ ‫هو‬‫و‬ ‫السيئات‬ ‫عن‬ ‫ويعفو‬)
  • 23.
  • 24. Lecture Let’s focus on Superclass’s Constructor 2
  • 25. Are superclass’s Constructor Inherited? o No. They are not inherited. o They are invoked explicitly or implicitly. o Explicitly using the super keyword. o A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass.
  • 26. Superclass’s Constructor Is Always Invoked o A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, public A(double d) { // some statements } is equivalent to public A(double d) { super(); // some statements } public A() { } is equivalent to public A() { super(); }
  • 27. Using the Keyword super o The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: 1. To call a superclass constructor 2. To call a superclass method
  • 28. Constructor Chaining o Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. o This is known as constructor chaining.
  • 29. public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } Trace Execution
  • 30. Overriding Methods in the Subclass o A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. o This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "nradius is " + radius; } }
  • 31. Overriding vs. Overloading public class Test { public static void main(String[] args) { A a = new A(); a.p(10); a.p(10.0); } } class B { public void p(double i) { System.out.println(i * 2); } } class A extends B { // This method overrides the method in B public void p(double i) { System.out.println(i); } } public class Test { public static void main(String[] args) { A a = new A(); a.p(10); a.p(10.0); } } class B { public void p(double i) { System.out.println(i * 2); } } class A extends B { // This method overloads the method in B public void p(int i) { System.out.println(i); } }
  • 32. Overriding vs. Overloading o The example above show the differences between overriding and overloading. o In (a), the method p(double i) in class A overrides the same method in class B. o In (b), the class A has two overloaded methods: p(double i) and p(int i). o The method p(double i) is inherited from B.
  • 33. Full Example Student Post Graduate Graduate • Have part time hours • Have a field training
  • 34. Full Example o Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. o This is known as constructor chaining.
  • 35. Full Example Methods of a subclass cannot directly access private members of their superclass. With inheritance, the common instance variables and methods of all the classes in the hierarchy are declared in a superclass. Use the protected access modifier when a superclass should provide a method only to its subclasses and other classes in the same package, but not to other clients.
  • 36. Full Example A subclass is more specific than its superclass and represents a smaller group of objects. A superclass's protected members have an intermediate level of protection between public and private access. They can be accessed by members of the superclass, by members of its subclasses and by members of other classes in the same package. A compilation error occurs if a subclass constructor calls one of its superclass constructors with arguments that do not match the superclass constructor declarations.
  • 37. Full Example In Java, the class hierarchy begins with class Object (in package java.lang), which every class in Java directly or indirectly extends. Invoking a superclass constructor’s name in a subclass causes a syntax error. Java requires that the statement that uses the keyword super appear first in the constructor. If a class is designed to be extended, it is better to provide a no-arg constructor to avoid programming errors.
  • 38. Practices Practice 1 Using charts, What is Inheritance ? Practice 2 Compare between the Types of Inheritance and which of them supported in java. Practice 3 By UML class, explain the concepts of Superclasses and Subclasses. Practice 4 Give 3 examples to explain Direct & Indirect Superclasses. Practice 5 Diffrenciate between "is-a" and the "has- a" relationship. Practice 6 Explain the Constructor Chaining using code.
  • 39. Practices Practice 7 True or false?  You can override a private method defined in a superclass.  You can override a static method defined in a superclass.  A subclass is a subset of a superclass. Practice 8 Write simple code:  What keyword do you use to define a subclass?  How do you explicitly invoke a superclass’s constructor from a subclass?  How do you invoke an overridden superclass method from a subclass? Practice 9 (In groups) Define The GeometricObject, Circle and Rectangle, based on the GeometricObject is the superclass for Circle Rectangle .
  • 40. THANKS! Any questions? You can find me at: Fb/mahmoudRAlfarra Staff.cst.ps/mfarra Youtube.com/mralfarra1 @mralfarra