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

20.2 Java inheritance

  • 1.
  • 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
  • 3.
  • 4.
  • 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 leadsto 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 isat the root of Java Class Hierarchy Java Platform Class Hierarchy 9
  • 10.
     Java supportsinheritance 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 takingall members from another class Inheritance - Derived Class 11 Person Student Employee Mother : Person Father : Person School: School Org: Organization Reusing Person
  • 12.
     You canaccess 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 arenot 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 derivedclass 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 hasa transitive relation Inheritance 15 class Person { … } class Student extends Person { … } class CollegeStudent extends Student { … } Person CollegeStudent Student
  • 16.
     In Javathere is no multiple inheritance  Only multiple interfaces can be implemented Multiple Inheritance 16 Person CollegeStudent Student
  • 17.
     Use thesuper 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 Checkyour solution here :https://judge.softuni.bg/Contests/1574/Inheritance-Lab
  • 19.
  • 20.
  • 21.
    Reusing Code atClass Level Reusing Classes
  • 22.
     Derived classescan 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 classescan 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 superand 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 childclass 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 froma 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 approachfor 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 canextend a class that we can't otherwise change Inheritance Benefits – Extension 29 Collections ArrayList CustomArrayList Extends
  • 30.
     Create anarray 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 ArrayList 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 ClassReuse Extension, Composition, Delegation
  • 33.
     Duplicate codeis error prone  Reuse classes through extension  Sometimes the only way Extension 33 Collections ArrayList CustomArrayList
  • 34.
     Using classesto define classes Composition 34 class Laptop { Monitor monitor; Touchpad touchpad; Keyboard keyboard; … } Reusing classes Laptop Monitor Touchpad Keyboard
  • 35.
    Delegation 35 class Laptop { Monitormonitor; void incrBrightness() { monitor.brighten(); } void decrBrightness() { monitor.dim(); } } Laptop increaseBrightness() decreaseBrightness() Monitor
  • 36.
     Create asimple 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 ofStrings 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 shareIS-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
  • 40.
  • 41.
  • 42.
  • 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