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
PPTX
Java Foundations: Maps, Lambda and Stream API
PPTX
17. Java data structures trees representation and traversal
PPTX
18. Java associative arrays
PPTX
Java Foundations: Methods
PPTX
Java Foundations: Data Types and Type Conversion
PPTX
20.3 Java encapsulation
PPTX
Dynamic memory allocation in c++
20.4 Java interfaces and abstraction
Java Foundations: Maps, Lambda and Stream API
17. Java data structures trees representation and traversal
18. Java associative arrays
Java Foundations: Methods
Java Foundations: Data Types and Type Conversion
20.3 Java encapsulation
Dynamic memory allocation in c++

What's hot (20)

PPT
Exception Handling
PPT
JAVA OOP
PPTX
Static Data Members and Member Functions
PPT
Inheritance : Extending Classes
PPTX
Inner class
PPT
JAVA Variables and Operators
PPT
standard template library(STL) in C++
PDF
C++ Files and Streams
PPSX
Collections - Array List
PPTX
inheritance c++
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
PPT
Java Collections Framework
PPTX
Super keyword in java
PPTX
Bloom filters
PPTX
Oop c++class(final).ppt
PDF
Classes and objects
PPT
Java Streams
PPT
Array in Java
PPTX
ArrayList in JAVA
PPTX
Inline function
Exception Handling
JAVA OOP
Static Data Members and Member Functions
Inheritance : Extending Classes
Inner class
JAVA Variables and Operators
standard template library(STL) in C++
C++ Files and Streams
Collections - Array List
inheritance c++
Java Foundations: Basic Syntax, Conditions, Loops
Java Collections Framework
Super keyword in java
Bloom filters
Oop c++class(final).ppt
Classes and objects
Java Streams
Array in Java
ArrayList in JAVA
Inline function
Ad

Similar to 20.2 Java inheritance (20)

PPT
RajLec10.ppt
Β 
PPTX
Java Inheritance - sub class constructors - Method overriding
PPTX
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
PPT
06 InheritanceAndPolymorphism.ppt
PPT
InheritanceAndPolymorphismprein Java.ppt
PDF
Java programming -Object-Oriented Thinking- Inheritance
PPT
Chapter 5 (OOP Principles).ppt
PPTX
UNIT 5.pptx
PPTX
OOPS_Unit2.inheritance and interface objected oriented programming
PPT
7_-_Inheritance
PPTX
Inheritance & interface ppt Inheritance
PPT
Inheritance & Polymorphism - 1
PPTX
Ch5 inheritance
PPTX
Inheritance in java
PPTX
Oop inheritance chapter 3
PPT
inheritance of java...basics of java in ppt
PPT
A457405934_21789_26_2018_Inheritance.ppt
PPTX
Pi j3.1 inheritance
PPTX
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RajLec10.ppt
Β 
Java Inheritance - sub class constructors - Method overriding
OBJECT ORIENTED PROGRAMMING STRUCU2.pptx
06 InheritanceAndPolymorphism.ppt
InheritanceAndPolymorphismprein Java.ppt
Java programming -Object-Oriented Thinking- Inheritance
Chapter 5 (OOP Principles).ppt
UNIT 5.pptx
OOPS_Unit2.inheritance and interface objected oriented programming
7_-_Inheritance
Inheritance & interface ppt Inheritance
Inheritance & Polymorphism - 1
Ch5 inheritance
Inheritance in java
Oop inheritance chapter 3
inheritance of java...basics of java in ppt
A457405934_21789_26_2018_Inheritance.ppt
Pi j3.1 inheritance
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
Ad

More from Intro C# Book (20)

PPTX
Java Problem solving
PPTX
21. Java High Quality Programming Code
PPTX
20.5 Java polymorphism
PPTX
20.1 Java working with abstraction
PPTX
19. Java data structures algorithms and complexity
PPTX
16. Java stacks and queues
PPTX
14. Java defining classes
PPTX
13. Java text processing
PPTX
12. Java Exceptions and error handling
PPTX
11. Java Objects and classes
PPTX
09. Java Methods
PPTX
05. Java Loops Methods and Classes
PPTX
07. Java Array, Set and Maps
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PPTX
02. Data Types and variables
PPTX
01. Introduction to programming with java
PPTX
23. Methodology of Problem Solving
PPTX
Chapter 22. Lambda Expressions and LINQ
PPTX
21. High-Quality Programming Code
PPTX
19. Data Structures and Algorithm Complexity
Java Problem solving
21. Java High Quality Programming Code
20.5 Java polymorphism
20.1 Java working with abstraction
19. Java data structures algorithms and complexity
16. Java stacks and queues
14. Java defining classes
13. Java text processing
12. Java Exceptions and error handling
11. Java Objects and classes
09. Java Methods
05. Java Loops Methods and Classes
07. Java Array, Set and Maps
03 and 04 .Operators, Expressions, working with the console and conditional s...
02. Data Types and variables
01. Introduction to programming with java
23. Methodology of Problem Solving
Chapter 22. Lambda Expressions and LINQ
21. High-Quality Programming Code
19. Data Structures and Algorithm Complexity

Recently uploaded (20)

PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPT
Ethics in Information System - Management Information System
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
Β 
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PDF
WebRTC in SignalWire - troubleshooting media negotiation
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PDF
Paper PDF World Game (s) Great Redesign.pdf
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PPTX
artificial intelligence overview of it and more
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PPTX
Introuction about WHO-FIC in ICD-10.pptx
PPTX
Internet___Basics___Styled_ presentation
PDF
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
PPTX
innovation process that make everything different.pptx
PPTX
newyork.pptxirantrafgshenepalchinachinane
PPTX
SAP Ariba Sourcing PPT for learning material
PPTX
Funds Management Learning Material for Beg
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
Ethics in Information System - Management Information System
Power Point - Lesson 3_2.pptx grad school presentation
Β 
introduction about ICD -10 & ICD-11 ppt.pptx
WebRTC in SignalWire - troubleshooting media negotiation
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
Paper PDF World Game (s) Great Redesign.pdf
Design_with_Watersergyerge45hrbgre4top (1).ppt
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
522797556-Unit-2-Temperature-measurement-1-1.pptx
artificial intelligence overview of it and more
SASE Traffic Flow - ZTNA Connector-1.pdf
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Introuction about WHO-FIC in ICD-10.pptx
Internet___Basics___Styled_ presentation
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
innovation process that make everything different.pptx
newyork.pptxirantrafgshenepalchinachinane
SAP Ariba Sourcing PPT for learning material
Funds Management Learning Material for Beg

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