Inheritance

Advanced Programming

SUT • Spring 2019

Outline

  • Inheritance

  • Class Hierarchies

  • is-a relationship

  • UML Class Diagram

  • protected members

  • Abstract Methods

  • super keyword

  • Initialization in inheritance

Introduction to Inheritance

Class Hierarchies

Class Hierarchies (2)

Class Hierarchies (3)

General and Specific Types

  • Faculty and Employee are both classes

  • Faculty is a more specific type of Employee

  • Employee is a more general type of Faculty

  • A Faculty instance is also a Employee instance

    • Dr. Felani is a faculty member

    • He is also an employee of university

is-a Relationship

  • More general class : Superclass

  • More specific class : Subclass

  • Subclass is inherited from superclass

  •  

  • Faculty is inherited from Employee

  • Rectangle is inherited from Shape

    • A rectangle is also a shape

  • Cat is inherited from Animal

    • Maloos is a cat, she is also an animal

Inheritance (2)

  • Name some other hierarchies…

  • Note: More specific type is also a class

    • Not an object

    • Ali Karimi is not a more specific type of FootballPlayer

      • He is an object

      • Not a class

Class Implementation

  • How do you implement Employee class?

  • How do you implement Faculty class?

Sample

public class Employee {
    private int salary;
    private Date birthDate;

    public void setName(String name) {
        // ....
    }

    public void setNationalID(String id) {
        // ....
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public int getSalary() {
        return salary;
    }
}

Sample

public class Faculty {
    private int salary;
    private Date birthDate;

    public void setName(String name) {
        // ....
    }

    public void setNationalID(String id) {
        // ....
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public int getSalary() {
        return salary;
    }

    // Faculty variables and methods
    private Course[] courses;
    public Course[] getOfferedCourses(){
        return courses;
    }
}

Inheritance in OOP

  • Java offers inheritance

  • like any object oriented programming language

  • Inheritance is used for implementing more specific classes

    • Duplicate code is eliminated

  • Inheritance provides code reuse

  • is-a relationship

Faculty & Employee

  • Faculty is inherited from Employee

  • Faculty extends Employee

  • Attributes and behaviors of Employee is inherited to Faculty

  • Inheritance provides code reuse

public class Faculty extends Employee{
    // Faculty variables and methods
    private Course[] courses;
    public Course[] getOfferedCourses(){
        return courses;
    }
}

UML Class Diagram

UML Class Diagram

Sample

class Shape {
    int color;
    int positionX, positionY;
}

class Circle extends Shape {
    private int radius;

    public double getArea() {
        return 3.14 * radius * radius;
    }
}

class Rectangle extends Shape {
    private int width, length;

    public double getArea() {
        return width * length;
    }
}

Terminology

  • Class Rectangle is inherited from class Shape

  • Rectangle is a subclass of Shape

  • Rectangle is a child of Shape

  • Rectangle is a derived class of Shape

  • Shape is the super-class of Rectangle

  • Shape is the parent of Rectangle

  • Shape is the base-class of Rectangle

  • Rectangle is-a Shape

Inheritance in java

  • Every class is inherited from class Object

    • Primitive-types are not objects

  • Object class has some operations

    • equals()

    • toString()

  • Every class adds some operations

  • And may changes some operations

    • toString()

Inheritance

  • Software reusability

  • Create new class from existing class

    • Absorb existing class’s data and behaviors

    • Enhance with new capabilities

  • Subclass extends superclass.

  • Subclass:

    • More specialized group of objects

    • Behaviors inherited from superclass

      • Or changed and customized

    • Additional behaviors

Class Hierarchy

  • Direct superclass

    • Inherited explicitly (one level up hierarchy)

  • Indirect superclass

    • Inherited two or more levels up hierarchy

  • Single inheritance

    • Inherits from one superclass

  • Multiple inheritance

    • Inherits from multiple superclasses

      • Java does not support multiple inheritance

is-a relationship

  • Object of subclass “is a” object of super-class

    • Example: Rectangle is quadrilateral.

    • Class Rectangle inherits from class Quadrilateral

    • Quadrilateral: superclass

    • Rectangle: subclass

  • Superclass typically represents larger set of objects than subclasses

    • superclass: Vehicle

    • subclass: Car

      • Smaller, more-specific subset of vehicles

More Examples

Superclass Subclass
Student GraduteStudent, UnderGraduateStudent
Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan, MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingAccount

Subclasses may…

  • Add new functionality

    • New members

  • Use inherited functionality

    • Software reuse

  • Override inherited functionality

    • Change parent methods

Software reuse

  • Software reuse is at the heart of inheritance

  • Using existing software components to create new ones

  • Capitalize on all the effort that went into the

    • design

    • implementation

    • and testing of the existing software

Bad smell

  • Avoid Copy & Paste!

  • Avoid Copy & Paste!

  • Avoid Copy & Paste!

  • Avoid Copy & Paste!

  • Avoid Copy & Paste!

  • Avoid Copy & Paste!

  • Avoid Copy & Paste!

  • Please, Avoid Copy & Paste!

Sample

public class Person {
    private String name;
    private Long nationalID;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getNationalID() {
        return nationalID;
    }

    public void setNationalID(Long nationalID) {
        this.nationalID = nationalID;
    }

    public void show() {
        System.out.println("example.Person: name=" + name
                + ",nationalID=" + nationalID);
    }
}

Sample

class Student extends Person {
    private String studentID;

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getStudentID() {
        return studentID;
    }

    public void takeCourse(Course course) {
    }

    public void show() {
        System.out.println("example.Student: name=" + getName()
                + ",nationalID=" + getNationalID()
                + ",studentID=" + studentID);
    }
}

new properties

new methods (more behaviour)

change parrent methods (override)

Sample

Person p1 = new Person();
p1.setName("Ali Alavi");
p1.setNationalID(1498670972L);
p1.show();


Student st = new Student();
st.setName("Ali Alavi");
st.setNationalID(1498670972L);
st.setStudentID("89072456");
st.show();

Defined in parent

Added in child

Changed in child

More About Inheritance

Abstract Behaviors

  • Does any animal swim?

    • No. So “to swim” is not a behavior of animals.

  • Any animal has a voice

  • “to talk” is a behavior of animals

  • But what is the voice of an animal?

  • How does an animal “talk”?

    • It depends to the specific type of animal

      • Dog: Hop! Hop!

      • Cat: Mewww!

Abstract Behaviors (2)

  • “talk” is an abstract behaviour of Animal

    • All animals can “talk”

    • But we can not specify how an animal talks

    • It depends to the specific class of animal

  • “talk” is a concrete behaviour of Dog

    • Hop! Hop!

  • “swim” is not a behaviour of Animal

    • All animals can not swim

    • “swim” is a concrete behaviour of Fish

Remember Shape Classes

Sample

public class Circle {
    private double radius;
    
    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public double getArea() {
        return Math.pow(radius, 2) * Math.PI;
    }

    public double getPerimeter() {
        return 2 * radius * Math.PI;
    }
}

Sample

public class Rectangle {
    private double width, length;
    
    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getArea() {
        return length * width;
    }

    public double getPerimeter() {
        return 2 * (length + width);
    }
}

Sample

public class Square {
    private double length;
    
    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getArea() {
        return length * length;
    }

    public double getPerimeter() {
        return 4 * length;
    }
}

Shapes Example

  • Shape is an abstract class

  • Some methods are undefined in Shape

  • Some methods should be defined in sub-classes

    • getArea()

    • getPerimeter()

  • These methods are abstract methods

    • Remember abstract behaviours

Abstract Methods

  • Shape classes

    • getArea()

    • draw()

  • Animals

    • Talk()

    • getName()

      • is not abstract!

  • How do you implement an abstract method?

  • We can implement these methods by simple dummy operations

  • Better way : abstract methods

Abstract Methods (2)

  • abstract method: no implementation

  • A class containing abstract methods: an abstract class

  • You can not instantiate abstract classes

    • Why?

  • If a sub-class do not implement the abstract method

    • It will be abstract too

Animal Example

abstract class Animal {
    private String name;

    protected Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public abstract String talk();
}

Animal Example

public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }

    public String talk() {
        return "Meowww";
    }
}

Access modifier in inheritance

  • You can not override a public method as a private method

    • Why?

  • It violates the “is-a” rule

  • You can not reduce accessibility of methods in subclasses

Accessibility of Members

  • Subclass has access to public members of parent class

    • Public methods and properties are accessible in subclass

    • Student used getName() and getStudentID()

  • Private members are not accessible in subclass

    • Student has no access to name and studentID properties

  • What if you want to let subclasses access a member, but not other classes?

Protected Members

  • Intermediate level of protection between public and packaged

  • protected members accessible by

    • subclass members

    • Class members in the same package

  • protected members are also package accessible

    • friendly

  • Protected variables and methods are shown with a # symbol in UML diagrams

Protected Members

Access Levels

  • Public

    • Accessible by all classes

  • Protected

    • Accessible by subclasses

    • Accessible by classes of the same package

  • Package access (friendly)

    • Accessible by classes of the same package

  • Private

    • No access

super Keyword

  • Access to parent members

  • The super reference can be used to refer to the parent class

  • super.f() invokes f() from parent class

  • Why we need it?

    • When the method is overridden in subclass

    • super is also used to invoke the parent's constructor

Application of super Keyword

class Student extends Person{
    public void show(){
	super.show();
	System.out.println(",studentID=" + studentID);
    }
}

Practice

class A {
    public int a;
}

public class B extends A {
    private in a;

    public void f() {
        int a;
        this.a = 5;
        super.a = 6;
        a = 4;

        System.out.println(a);
        System.out.println(this.a);
        System.out.println(super.a);
    }

    public static void main(String[] args){
        new B().f();
    }
}

Object class methods

  • equals()

  • toString()

  • finalize()

  •  

  • We can override these methods in our classes

Multiple Inheritance

  • Java supports single inheritance

  • Derived class can have only one parent class

  • Multiple inheritance allows a class to be derived from two or more classes

    • inheriting the members of all parents

  • Collisions, such as the same variable name in two parents, have to be resolved

  • Java does not support multiple inheritance

  • The use of interfaces usually gives us aspects of multiple inheritance without the overhead

Initialization

  • Constructors are not inherited

    • even though they have public visibility

  • We often want to use the parent's constructor to set up the "parent's part" of the object

super("Ali");

Constructors

  • A child’s constructor is responsible for calling the parent’s constructor

  • It is done using super keyword

  • The first statement of a child’s constructor should be the super reference to call the parent constructor

  • Otherwise, default constructor is implicitly invoked

  • If default constructor does not exist? (how?!)

    • A syntax error

    • You should explicitly call an appropriate parent constructor

Sample

class Person {
    private String name;
    private Long nationalID;

    public Person(String name, Long nationalID) {
        this.name = name;
        this.nationalID = nationalID;
    }
}

class Student extends Person {
    private String studentID;

    public Student(String name, Long naID, String stID) {
        super(name, naID);
        this.studentID = stID;
    }
}


public class Main {
    public static void main(String[] args) {
        Person p1 = new Person();
        System.out.println(p1.toString());
        Student st = new Student("Ali Alavi", 1498670972L, "89072456");
    }
}

Order of initialization

  • Once per class

    • Static variable declaration of parent

    • Static block of parent

    • Static variable declaration

    • Static block

  • Once per object

    • variable declaration of parent

    • Initialization block of parent

    • Constructor of parent

    • variable declaration

    • Initialization block

    • Constructor

Practice

public class Parent {
    static int a = A();
    static{
    	a=B();
    }
    int b = E();
    {
    	b = F();
    }
    public Parent(){
    	b = G();
    }
}
class Child extends Parent{
    static int c = C();
    static{
    	c=D();
    }
    int b = H();
    {
    	b = I();
    }
    public Child(){
    	b = J();
    }
}

What happens if we invoke: new Child();

Title Text

Made with Slides.com