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
Ad

More Related Content

What's hot (20)

Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
Vishesh Jha
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Array in Java
Array in JavaArray in Java
Array in Java
Shehrevar Davierwala
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
sameer farooq
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Darpan Chelani
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
kunal kishore
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
Nishan Barot
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 

Similar to 20.2 Java inheritance (20)

Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
chetanpatilcp783
 
OOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programmingOOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programming
ssuserf45a65
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
yash jain
 
Inheritance & interface ppt Inheritance
Inheritance & interface ppt  InheritanceInheritance & interface ppt  Inheritance
Inheritance & interface ppt Inheritance
narikamalliy
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
Bharat Kalia
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
CurativeServiceDivis
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
sonukumarjha12
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).pptM251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3
Narayana Swamy
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Inheritance Interface and Packags in java programming.pptx
Inheritance Interface and Packags in java programming.pptxInheritance Interface and Packags in java programming.pptx
Inheritance Interface and Packags in java programming.pptx
Prashant416351
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
Inheritance used in java
Inheritance used in javaInheritance used in java
Inheritance used in java
TharuniDiddekunta
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUIChapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Inheritance
InheritanceInheritance
Inheritance
JayanthiNeelampalli
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
OOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programmingOOPS_Unit2.inheritance and interface objected oriented programming
OOPS_Unit2.inheritance and interface objected oriented programming
ssuserf45a65
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
yash jain
 
Inheritance & interface ppt Inheritance
Inheritance & interface ppt  InheritanceInheritance & interface ppt  Inheritance
Inheritance & interface ppt Inheritance
narikamalliy
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
Bharat Kalia
 
M251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).pptM251_Meeting 5 (Inheritance and Polymorphism).ppt
M251_Meeting 5 (Inheritance and Polymorphism).ppt
smartashammari
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3
Narayana Swamy
 
Inheritance Interface and Packags in java programming.pptx
Inheritance Interface and Packags in java programming.pptxInheritance Interface and Packags in java programming.pptx
Inheritance Interface and Packags in java programming.pptx
Prashant416351
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUIChapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Ad

More from Intro C# Book (20)

Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
Intro C# Book
 
Ad

Recently uploaded (15)

美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
Taqyea
 
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and MonitoringPresentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
mdaoudi
 
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
Taqyea
 
Paper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdfPaper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdf
Steven McGee
 
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdfGiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
Giacomo Vacca
 
ProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptxProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptx
OlenaKotovska
 
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
werhkr1
 
IoT PPT introduction to internet of things
IoT PPT introduction to internet of thingsIoT PPT introduction to internet of things
IoT PPT introduction to internet of things
VaishnaviPatil3995
 
introduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.pptintroduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.ppt
SherifElGohary7
 
AG-FIRMA Ai Agent for Agriculture | RAG ..
AG-FIRMA Ai Agent for Agriculture  | RAG ..AG-FIRMA Ai Agent for Agriculture  | RAG ..
AG-FIRMA Ai Agent for Agriculture | RAG ..
Anass Nabil
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Breaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdfBreaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdf
Internet Bundle Now
 
Cloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptxCloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptx
marketing140789
 
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
emestica1
 
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness GuideThe Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
russellpeter1995
 
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
Taqyea
 
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and MonitoringPresentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
mdaoudi
 
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
Taqyea
 
Paper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdfPaper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdf
Steven McGee
 
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdfGiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
Giacomo Vacca
 
ProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptxProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptx
OlenaKotovska
 
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
werhkr1
 
IoT PPT introduction to internet of things
IoT PPT introduction to internet of thingsIoT PPT introduction to internet of things
IoT PPT introduction to internet of things
VaishnaviPatil3995
 
introduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.pptintroduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.ppt
SherifElGohary7
 
AG-FIRMA Ai Agent for Agriculture | RAG ..
AG-FIRMA Ai Agent for Agriculture  | RAG ..AG-FIRMA Ai Agent for Agriculture  | RAG ..
AG-FIRMA Ai Agent for Agriculture | RAG ..
Anass Nabil
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Breaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdfBreaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdf
Internet Bundle Now
 
Cloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptxCloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptx
marketing140789
 
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
emestica1
 
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness GuideThe Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
russellpeter1995
 

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

  翻译: