SlideShare a Scribd company logo
Inheritance
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Extending Classes
Table of Contents
1. Inheritance
2. Class Hierarchies
3. Inheritance in Java
4. Accessing Members of the Base Class
5. Types of Class Reuse
 Extension, Composition, Delegation
6. When to Use Inheritance
2
sli.do
#java-advanced
Have a Question?
Inheritance
Extending Classes
 Superclass - Parent class, Base Class
 The class giving its members to its child
class
 Subclass - Child class, Derived Class
 The class taking members from its base class
Inheritance
5
Superclass
Subclass
Derived
Base
Inheritance – Example
6
Person
+Name: String
+Address: String
Employee
+Company: String
Student
+School: String
Derived class Derived class
Base class
 Inheritance leads to hierarchies of classes and/or interfaces in
an application:
Class Hierarchies
7
Game
MultiplePlayersGame
BoardGame
Chess Backgammon
SinglePlayerGame
Minesweeper Solitaire
Base class holds
common characteristics
…
…
Class Hierarchies – Java Collection
8
Collection
Queue
Deque
ArrayDeque
HashSet
List
ArrayList PriorityQueue
Iterable
Set
LinkedList
Vector
Stack
LinkedHashSet
SortedSet
TreeSet
 Object is at the root of Java Class Hierarchy
Java Platform Class Hierarchy
9
 Java supports inheritance through extends keyword
Inheritance in Java
10
class Person { … }
class Student extends Person { … }
class Employee extends Person { … }
Person
Employee
Student extends
Person
Student
 Class taking all members from another class
Inheritance - Derived Class
11
Person
Student Employee
Mother : Person
Father : Person
School: School Org: Organization
Reusing
Person
 You can access inherited members
Using Inherited Members
12
class Person { public void sleep() { … } }
class Student extends Person { … }
class Employee extends Person { … }
Student student = new Student();
student.sleep();
Employee employee = new Employee();
employee.sleep();
 Constructors are not inherited
 Constructors can be reused by the child classes
Reusing Constructors
13
class Student extends Person {
private School school;
public Student(String name, School school) {
super(name);
this.school = school;
}
}
Constructor call
should be first
 A derived class instance contains an instance of its base class
Thinking About Inheritance - Extends
14
Employee
(Derived Class)
+work():void
Student (Derived Class)
+study():void
Person
(Base Class)
+sleep():void
 Inheritance has a transitive relation
Inheritance
15
class Person { … }
class Student extends Person { … }
class CollegeStudent extends Student { … }
Person
CollegeStudent
Student
 In Java there is no multiple inheritance
 Only multiple interfaces can be implemented
Multiple Inheritance
16
Person
CollegeStudent
Student
 Use the super keyword
Access to Base Class Members
17
class Person { … }
class Employee extends Person {
public void fire(String reasons) {
System.out.println(
super.name +
" got fired because " + reasons);
}
}
Problem: Single Inheritance
18
Animal
+eat():void
Dog
+bark():void
Check your solution here :https://judge.softuni.bg/Contests/1574/Inheritance-Lab
Problem: Multiple Inheritance
19
Animal
+eat():void
Dog
+bark():void
Puppy
+weep():void
Problem: Hierarchical Inheritance
20
Animal
+eat():void
Dog
+bark():void
Cat
+meow():void
Reusing Code at Class Level
Reusing Classes
 Derived classes can access all public and protected members
 Derived classes can access default members if in same package
 Private fields aren't inherited in subclasses (can't be accesssed)
Inheritance and Access Modifiers
22
class Person {
protected String address;
public void sleep();
String name;
private String id;
}
Can be accessed
through other methods
 Derived classes can hide superclass variables
Shadowing Variables
23
class Patient extends Person {
protected float weight;
public void method() {
double weight = 0.5d;
}
}
class Person { protected int weight; }
hides int weight
hides both
 Use super and this to specify member access
Shadowing Variables - Access
24
class Patient extends Person {
protected float weight;
public void method() {
double weight = 0.5d;
this.weight = 0.6f;
super.weight = 1;
}
}
class Person { protected int weight; }
Instance member
Base class member
Local variable
 A child class can redefine existing methods
Overriding Derived Methods
25
public class Person {
public void sleep() {
System.out.println("Person sleeping"); }
}
public class Student extends Person {
@Override
public void sleep(){
System.out.println("Student sleeping"); }
}
Signature and return
type should match
Method in base class must not be final
 final – defines a method that can't be overridden
Final Methods
26
public class Animal {
public final void eat() { … }
}
public class Dog extends Animal {
@Override
public void eat() {} // Error…
}
 Inheriting from a final classes is forbidden
Final Classes
27
public final class Animal {
…
}
public class Dog extends Animal { } // Error…
public class MyString extends String { } // Error…
public class MyMath extends Math { } // Error…
 One approach for providing abstraction
Inheritance Benefits - Abstraction
28
Person person = new Person();
Student student = new Student();
List<Person> people = new ArrayList();
people.add(person);
people.add(student);
Student (Derived Class)
Person (Base Class)
Focus on common
properties
 We can extend a class that we can't otherwise change
Inheritance Benefits – Extension
29
Collections
ArrayList
CustomArrayList
Extends
 Create an array list that has
 All functionality of an ArrayList
 Function that returns and removes a random element
Problem: Random Array List
30
Collections
ArrayList
RandomArrayList
+getRandomElement():Object
Solution: Random Array List
31
public class RandomArrayList extends ArrayList {
private Random rnd; // Initialize this…
public Object getRandomElement() {
int index = this.rnd.nextInt(super.size());
Object element = super.get(index);
super.remove(index);
return element;
}
}
Types of Class Reuse
Extension, Composition, Delegation
 Duplicate code is error prone
 Reuse classes through extension
 Sometimes the only way
Extension
33
Collections
ArrayList
CustomArrayList
 Using classes to define classes
Composition
34
class Laptop {
Monitor monitor;
Touchpad touchpad;
Keyboard keyboard;
…
} Reusing classes
Laptop
Monitor
Touchpad
Keyboard
Delegation
35
class Laptop {
Monitor monitor;
void incrBrightness() {
monitor.brighten();
}
void decrBrightness() {
monitor.dim();
}
}
Laptop
increaseBrightness()
decreaseBrightness()
Monitor
 Create a simple Stack class which can store only strings
Problem: Stack of Strings
36
StackOfStrings
-data: List<String>
+push(String) :void
+pop(): String
+peek(): String
+isEmpty(): boolean
StackOfStrings
ArrayList
Solution: Stack of Strings
37
public class StackOfStrings {
private List<String> container;
// TODO: Create a constructor
public void push(String item) { this.container.add(item); }
public String pop() {
// TODO: Validate if list is not empty
return this.container.remove(this.container.size() - 1);
}
}
 Classes share IS-A relationship
 Derived class IS-A-SUBSTITUTE for the base class
 Share the same role
 Derived class is the same as the base class but adds a little bit
more functionality
When to Use Inheritance
38
Too simplistic
 …
 …
 …
Summary
39
 Inheritance is a powerful tool for code reuse
 Subclass inherits members from Superclass
 Subclass can override methods
 Look for classes with the same role
 Look for IS-A and IS-A-SUBSTITUTE for relationship
 Consider Composition and Delegation instead
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
License
44

More Related Content

PPTX
20.4 Java interfaces and abstraction
Intro C# Book
 
PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PPTX
Java Foundations: Methods
Svetlin Nakov
 
PDF
Java 8 Default Methods
Haim Michael
 
PPTX
16. Java stacks and queues
Intro C# Book
 
PPTX
18. Java associative arrays
Intro C# Book
 
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
Intro C# Book
 
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Java Foundations: Methods
Svetlin Nakov
 
Java 8 Default Methods
Haim Michael
 
16. Java stacks and queues
Intro C# Book
 
18. Java associative arrays
Intro C# Book
 

What's hot (20)

PPTX
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
PPTX
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
PPT
Core java concepts
Ram132
 
PPTX
Java Foundations: Arrays
Svetlin Nakov
 
PPT
Collections Framework
Sunil OS
 
PPT
JAVA OOP
Sunil OS
 
PPT
Java collection
Arati Gadgil
 
PPT
PDBC
Sunil OS
 
PPTX
09. Java Methods
Intro C# Book
 
PPT
JavaScript
Sunil OS
 
PPTX
Polymorphism in java
sureshraj43
 
PDF
Polymorphism In Java
Spotle.ai
 
PPT
Method overriding
Azaz Maverick
 
PPT
Object Oriented Programming with Java
backdoor
 
PPT
Java Basics V3
Sunil OS
 
PDF
Object Oriented Programming - 5. Class & Object
AndiNurkholis1
 
PPTX
Constructor ppt
Vinod Kumar
 
PDF
Java String
Java2Blog
 
PDF
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
PPT
JDBC
Sunil OS
 
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Core java concepts
Ram132
 
Java Foundations: Arrays
Svetlin Nakov
 
Collections Framework
Sunil OS
 
JAVA OOP
Sunil OS
 
Java collection
Arati Gadgil
 
PDBC
Sunil OS
 
09. Java Methods
Intro C# Book
 
JavaScript
Sunil OS
 
Polymorphism in java
sureshraj43
 
Polymorphism In Java
Spotle.ai
 
Method overriding
Azaz Maverick
 
Object Oriented Programming with Java
backdoor
 
Java Basics V3
Sunil OS
 
Object Oriented Programming - 5. Class & Object
AndiNurkholis1
 
Constructor ppt
Vinod Kumar
 
Java String
Java2Blog
 
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
JDBC
Sunil OS
 
Ad

Similar to 20.2 Java inheritance (20)

PPTX
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
JeevaR43
 
PPTX
Detailed_description_on_java_ppt_final.pptx
technicaljd3
 
PPT
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
PPTX
Chap-3 Inheritance.pptx
chetanpatilcp783
 
PPTX
OOPS_Unit2.inheritance and interface objected oriented programming
ssuserf45a65
 
PPTX
Inheritance in java
yash jain
 
PPTX
Inheritance & interface ppt Inheritance
narikamalliy
 
PPTX
20.5 Java polymorphism
Intro C# Book
 
PPTX
Object oriented programming Fundamental Concepts
Bharat Kalia
 
PPTX
UNIT 5.pptx
CurativeServiceDivis
 
PPTX
inheritance.pptx
sonukumarjha12
 
PPT
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
PPTX
Oop inheritance chapter 3
Narayana Swamy
 
PPTX
Unit3 part2-inheritance
DevaKumari Vijay
 
PPTX
Inheritance Interface and Packags in java programming.pptx
Prashant416351
 
PPT
20 Object-oriented programming principles
maznabili
 
PDF
Inheritance used in java
TharuniDiddekunta
 
PPTX
Core java oop
Parth Shah
 
PPTX
Inheritance Slides
Ahsan Raja
 
PPTX
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
JeevaR43
 
Detailed_description_on_java_ppt_final.pptx
technicaljd3
 
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Chap-3 Inheritance.pptx
chetanpatilcp783
 
OOPS_Unit2.inheritance and interface objected oriented programming
ssuserf45a65
 
Inheritance in java
yash jain
 
Inheritance & interface ppt Inheritance
narikamalliy
 
20.5 Java polymorphism
Intro C# Book
 
Object oriented programming Fundamental Concepts
Bharat Kalia
 
inheritance.pptx
sonukumarjha12
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
Oop inheritance chapter 3
Narayana Swamy
 
Unit3 part2-inheritance
DevaKumari Vijay
 
Inheritance Interface and Packags in java programming.pptx
Prashant416351
 
20 Object-oriented programming principles
maznabili
 
Inheritance used in java
TharuniDiddekunta
 
Core java oop
Parth Shah
 
Inheritance Slides
Ahsan Raja
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Ad

More from Intro C# Book (20)

PPTX
17. Java data structures trees representation and traversal
Intro C# Book
 
PPTX
Java Problem solving
Intro C# Book
 
PPTX
21. Java High Quality Programming Code
Intro C# Book
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PPTX
19. Java data structures algorithms and complexity
Intro C# Book
 
PPTX
14. Java defining classes
Intro C# Book
 
PPTX
13. Java text processing
Intro C# Book
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
PPTX
11. Java Objects and classes
Intro C# Book
 
PPTX
05. Java Loops Methods and Classes
Intro C# Book
 
PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
01. Introduction to programming with java
Intro C# Book
 
PPTX
23. Methodology of Problem Solving
Intro C# Book
 
PPTX
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
PPTX
21. High-Quality Programming Code
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
PPTX
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
Intro C# Book
 
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
Intro C# Book
 
14. Java defining classes
Intro C# Book
 
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
Intro C# Book
 
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
16. Arrays Lists Stacks Queues
Intro C# Book
 

Recently uploaded (20)

PDF
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
PPTX
Pengenalan perangkat Jaringan komputer pada teknik jaringan komputer dan tele...
Prayudha3
 
PPTX
Google SGE SEO: 5 Critical Changes That Could Wreck Your Rankings in 2025
Reversed Out Creative
 
PPTX
原版北不列颠哥伦比亚大学毕业证文凭UNBC成绩单2025年新版在线制作学位证书
e7nw4o4
 
PDF
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
LABUAN 4D
 
PPTX
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
PPTX
Black Yellow Modern Minimalist Elegant Presentation.pptx
nothisispatrickduhh
 
PPTX
B2B_Ecommerce_Internship_Simranpreet.pptx
LipakshiJindal
 
PDF
Project English Paja Jara Alejandro.jpdf
AlejandroAlonsoPajaJ
 
PPTX
Blue and Dark Blue Modern Technology Presentation.pptx
ap177979
 
PPTX
ENCOR_Chapter_10 - OSPFv3 Attribution.pptx
nshg93
 
PDF
“Google Algorithm Updates in 2025 Guide”
soohhhnah
 
PDF
Centralized Business Email Management_ How Admin Controls Boost Efficiency & ...
XgenPlus Technologies
 
PPTX
LESSON-2-Roles-of-ICT-in-Teaching-for-learning_123922 (1).pptx
renavieramopiquero
 
PPTX
SEO Trends in 2025 | B3AITS - Bow & 3 Arrows IT Solutions
B3AITS - Bow & 3 Arrows IT Solutions
 
PDF
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
PPT
Transformaciones de las funciones elementales.ppt
rirosel211
 
PPTX
AI ad its imp i military life read it ag
ShwetaBharti31
 
PPTX
Different Generation Of Computers .pptx
divcoder9507
 
PDF
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
Pengenalan perangkat Jaringan komputer pada teknik jaringan komputer dan tele...
Prayudha3
 
Google SGE SEO: 5 Critical Changes That Could Wreck Your Rankings in 2025
Reversed Out Creative
 
原版北不列颠哥伦比亚大学毕业证文凭UNBC成绩单2025年新版在线制作学位证书
e7nw4o4
 
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
LABUAN 4D
 
Microsoft PowerPoint Student PPT slides.pptx
Garleys Putin
 
Black Yellow Modern Minimalist Elegant Presentation.pptx
nothisispatrickduhh
 
B2B_Ecommerce_Internship_Simranpreet.pptx
LipakshiJindal
 
Project English Paja Jara Alejandro.jpdf
AlejandroAlonsoPajaJ
 
Blue and Dark Blue Modern Technology Presentation.pptx
ap177979
 
ENCOR_Chapter_10 - OSPFv3 Attribution.pptx
nshg93
 
“Google Algorithm Updates in 2025 Guide”
soohhhnah
 
Centralized Business Email Management_ How Admin Controls Boost Efficiency & ...
XgenPlus Technologies
 
LESSON-2-Roles-of-ICT-in-Teaching-for-learning_123922 (1).pptx
renavieramopiquero
 
SEO Trends in 2025 | B3AITS - Bow & 3 Arrows IT Solutions
B3AITS - Bow & 3 Arrows IT Solutions
 
PDF document: World Game (s) Great Redesign.pdf
Steven McGee
 
Transformaciones de las funciones elementales.ppt
rirosel211
 
AI ad its imp i military life read it ag
ShwetaBharti31
 
Different Generation Of Computers .pptx
divcoder9507
 
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 

20.2 Java inheritance

  • 2. Table of Contents 1. Inheritance 2. Class Hierarchies 3. Inheritance in Java 4. Accessing Members of the Base Class 5. Types of Class Reuse  Extension, Composition, Delegation 6. When to Use Inheritance 2
  • 5.  Superclass - Parent class, Base Class  The class giving its members to its child class  Subclass - Child class, Derived Class  The class taking members from its base class Inheritance 5 Superclass Subclass Derived Base
  • 6. Inheritance – Example 6 Person +Name: String +Address: String Employee +Company: String Student +School: String Derived class Derived class Base class
  • 7.  Inheritance leads to hierarchies of classes and/or interfaces in an application: Class Hierarchies 7 Game MultiplePlayersGame BoardGame Chess Backgammon SinglePlayerGame Minesweeper Solitaire Base class holds common characteristics … …
  • 8. Class Hierarchies – Java Collection 8 Collection Queue Deque ArrayDeque HashSet List ArrayList PriorityQueue Iterable Set LinkedList Vector Stack LinkedHashSet SortedSet TreeSet
  • 9.  Object is at the root of Java Class Hierarchy Java Platform Class Hierarchy 9
  • 10.  Java supports inheritance through extends keyword Inheritance in Java 10 class Person { … } class Student extends Person { … } class Employee extends Person { … } Person Employee Student extends Person Student
  • 11.  Class taking all members from another class Inheritance - Derived Class 11 Person Student Employee Mother : Person Father : Person School: School Org: Organization Reusing Person
  • 12.  You can access inherited members Using Inherited Members 12 class Person { public void sleep() { … } } class Student extends Person { … } class Employee extends Person { … } Student student = new Student(); student.sleep(); Employee employee = new Employee(); employee.sleep();
  • 13.  Constructors are not inherited  Constructors can be reused by the child classes Reusing Constructors 13 class Student extends Person { private School school; public Student(String name, School school) { super(name); this.school = school; } } Constructor call should be first
  • 14.  A derived class instance contains an instance of its base class Thinking About Inheritance - Extends 14 Employee (Derived Class) +work():void Student (Derived Class) +study():void Person (Base Class) +sleep():void
  • 15.  Inheritance has a transitive relation Inheritance 15 class Person { … } class Student extends Person { … } class CollegeStudent extends Student { … } Person CollegeStudent Student
  • 16.  In Java there is no multiple inheritance  Only multiple interfaces can be implemented Multiple Inheritance 16 Person CollegeStudent Student
  • 17.  Use the super keyword Access to Base Class Members 17 class Person { … } class Employee extends Person { public void fire(String reasons) { System.out.println( super.name + " got fired because " + reasons); } }
  • 18. Problem: Single Inheritance 18 Animal +eat():void Dog +bark():void Check your solution here :https://judge.softuni.bg/Contests/1574/Inheritance-Lab
  • 21. Reusing Code at Class Level Reusing Classes
  • 22.  Derived classes can access all public and protected members  Derived classes can access default members if in same package  Private fields aren't inherited in subclasses (can't be accesssed) Inheritance and Access Modifiers 22 class Person { protected String address; public void sleep(); String name; private String id; } Can be accessed through other methods
  • 23.  Derived classes can hide superclass variables Shadowing Variables 23 class Patient extends Person { protected float weight; public void method() { double weight = 0.5d; } } class Person { protected int weight; } hides int weight hides both
  • 24.  Use super and this to specify member access Shadowing Variables - Access 24 class Patient extends Person { protected float weight; public void method() { double weight = 0.5d; this.weight = 0.6f; super.weight = 1; } } class Person { protected int weight; } Instance member Base class member Local variable
  • 25.  A child class can redefine existing methods Overriding Derived Methods 25 public class Person { public void sleep() { System.out.println("Person sleeping"); } } public class Student extends Person { @Override public void sleep(){ System.out.println("Student sleeping"); } } Signature and return type should match Method in base class must not be final
  • 26.  final – defines a method that can't be overridden Final Methods 26 public class Animal { public final void eat() { … } } public class Dog extends Animal { @Override public void eat() {} // Error… }
  • 27.  Inheriting from a final classes is forbidden Final Classes 27 public final class Animal { … } public class Dog extends Animal { } // Error… public class MyString extends String { } // Error… public class MyMath extends Math { } // Error…
  • 28.  One approach for providing abstraction Inheritance Benefits - Abstraction 28 Person person = new Person(); Student student = new Student(); List<Person> people = new ArrayList(); people.add(person); people.add(student); Student (Derived Class) Person (Base Class) Focus on common properties
  • 29.  We can extend a class that we can't otherwise change Inheritance Benefits – Extension 29 Collections ArrayList CustomArrayList Extends
  • 30.  Create an array list that has  All functionality of an ArrayList  Function that returns and removes a random element Problem: Random Array List 30 Collections ArrayList RandomArrayList +getRandomElement():Object
  • 31. Solution: Random Array List 31 public class RandomArrayList extends ArrayList { private Random rnd; // Initialize this… public Object getRandomElement() { int index = this.rnd.nextInt(super.size()); Object element = super.get(index); super.remove(index); return element; } }
  • 32. Types of Class Reuse Extension, Composition, Delegation
  • 33.  Duplicate code is error prone  Reuse classes through extension  Sometimes the only way Extension 33 Collections ArrayList CustomArrayList
  • 34.  Using classes to define classes Composition 34 class Laptop { Monitor monitor; Touchpad touchpad; Keyboard keyboard; … } Reusing classes Laptop Monitor Touchpad Keyboard
  • 35. Delegation 35 class Laptop { Monitor monitor; void incrBrightness() { monitor.brighten(); } void decrBrightness() { monitor.dim(); } } Laptop increaseBrightness() decreaseBrightness() Monitor
  • 36.  Create a simple Stack class which can store only strings Problem: Stack of Strings 36 StackOfStrings -data: List<String> +push(String) :void +pop(): String +peek(): String +isEmpty(): boolean StackOfStrings ArrayList
  • 37. Solution: Stack of Strings 37 public class StackOfStrings { private List<String> container; // TODO: Create a constructor public void push(String item) { this.container.add(item); } public String pop() { // TODO: Validate if list is not empty return this.container.remove(this.container.size() - 1); } }
  • 38.  Classes share IS-A relationship  Derived class IS-A-SUBSTITUTE for the base class  Share the same role  Derived class is the same as the base class but adds a little bit more functionality When to Use Inheritance 38 Too simplistic
  • 39.  …  …  … Summary 39  Inheritance is a powerful tool for code reuse  Subclass inherits members from Superclass  Subclass can override methods  Look for classes with the same role  Look for IS-A and IS-A-SUBSTITUTE for relationship  Consider Composition and Delegation instead
  • 43.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 44.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license License 44

Editor's Notes