Week 8 Lecture -3 Inheritance and Polymorphism

Slides:



Advertisements
Similar presentations
Chapter 1 Inheritance University Of Ha’il.
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
1 Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding l Object:
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
1 Introduction to Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding.
Inheritance using Java
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Inheritance The Basics in Java. Definition  A class that is derived from another class is called a subclass (also a derived class, extended class, or.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Topics Inheritance introduction
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
Inheritance.
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Lecture 12 Inheritance.
Inheritance-Basics.
Inheritance and Polymorphism
Inheritance in Java.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Modern Programming Tools And Techniques-I Inheritance
OOP’S Concepts in C#.Net
CSC 143 Inheritance.
Chapter 9 Inheritance and Polymorphism
Inheritance Chapter 5.
More inheritance, Abstract Classes and Interfaces
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Inheritance, Polymorphism, and Interfaces. Oh My
Advanced Programming Behnam Hatami Fall 2017.
METHOD OVERRIDING in JAVA
Java – Inheritance.
Inheritance Inheritance is a fundamental Object Oriented concept
Inheritance Cse 3rd year.
Java Programming, Second Edition
Java Inheritance.
Chapter 10: Method Overriding and method Overloading
Lecture 6 Inheritance CSE /26/2018.
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism
Method Overriding and method Overloading
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Topics OOP Review Inheritance Review Abstract Classes
Lecture 6 Inheritance CSE /26/2018.
C++ Object Oriented 1.
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Week 8 Lecture -3 Inheritance and Polymorphism 1

Lecture Outline Inheritance Inheritance in Java Definition and basic terminology Various forms of Inheritance Inheritance in Java examples use of the super keyword access modifier (perhaps recap) method overriding (vs. overloading) Object class and toString() method 2

Inheritance 3

Inheritance contd. Inheritance: It a parent-child (is-a) relationship between classes The concept allows sharing of the behavior of the parent class into its child classes – Code reuse Child class can add new behavior or override existing behavior from parent (to be more specilaised) 4

Inheritance contd. Inheritance creates is-a relation. – if A is-a B - than A could extend B Head is-a Lecturer. Everything that a lecturer can do, the Head also can do. Head has all the functionality of a Lecturer and some more. 5

Inheritance terminology Super class/Base class/Parent class: terms to describe the parent in the relationship, which shares its functionality Sub class/Derived class/Child class: terms to describe the child in the relationship, which accepts functionality from its parent Extended/Inherited/Derived: become a subclass of another class 6

Various forms…of Inheritance Animal Cat Single Inheritance: one derived class inherits from one base class. 7

Various forms…of Inheritance contd. Animal Cat PersianCat Multilevel Inheritance: subclass acts as a base class for other classes ©Abdur Rakib 2017 8

Various forms…of Inheritance contd. Animal Cat Donkey Horse PersianCat Hierarchical Inheritance: multiple subclasses inherit from one base class. 9

Various forms…of Inheritance contd. Animal Cat Donkey Horse PersianCat Mule Multiple Inheritance: Java does not support multiple inheritance. Other languages (C++) allow multiple inheritance

Inheritance in Java In Java, inheritance is implemented using the keyword extends public class Cat extends Animal{ } the objects of Cat class will now receive all of the state (fields) and behavior (methods) of the parent class Animal constructors and static methods/fields are not inherited by default, a class's parent is Object

Inheritance Example Animal +eat(): void Cat +meow(): void

Animal example Java code class Animal{ public void eat(){ System.out.println("eating...");} } class Cat extends Animal{ public void meow(){ System.out.println("meowing..."); class TestAnimal{ public static void main(String args[]){ Cat cat=new Cat(); cat.meow(); cat.eat(); Output: meowing... eating... } 13

Animal example Java code class Animal{ public void eat(){ System.out.println("eating...");} } class Cat extends Animal{ String name; public Cat(String name){ this.name=name; public void meow(){ System.out.println(name+" meowing...");} class TestAnimal{ public static void main(String args[]){ Cat cat=new Cat("Bela"); cat.meow(); cat.eat(); } ©Abdur Rakib 2017

Animal example Java code class Animal{ public void eat(){ System.out.println("eating...");} } class Cat extends Animal{ String name; public Cat(String name){ this.name=name; public void meow(){ System.out.println(name+" meowing...");} class TestAnimal{ public static void main(String args[]){ Cat cat=new Cat("Bela"); cat.meow(); cat.eat(); } Output: Bela meowing... eating...

Hierarchical Inheritance Example Animal -weight: int -name: String +getWeight(): void Cat +meow(): void Bird + fly() : void

Animal example Java code public class Animal { int weight; String name; // constructor public Animal(){} public Animal(int weight, String name) { this.weight = weight; this.name = name; } // methods public void getWeight() System.out.println(name+"’s weight: " + weight);

Animal example Java code contd. class Cat extends Animal { public Cat(int weight, String name) super(weight, name); } public void meow() System.out.println(name+ " meowing");

Animal example Java code contd. class Bird extends Animal { public Bird(int weight, String name) super(weight, name); } public void fly() System.out.println(name+ " flying");

Animal example Java code class TestAnimal { public static void main(String args[]) { Animal animal = new Animal(); Cat cat = new Cat(500, "Bela"); Bird bird = new Bird(50, "Happy"); cat.getWeight(); cat.meow(); bird.getWeight(); bird.fly(); } Output: Bela’s weight: 500 Bela meowing Happy’s weight: 50 Happy flying

Animal example Java code class TestAnimal { public static void main(String args[]) { Animal animal = new Animal(); Cat cat = new Cat(500, "Bela"); Bird bird = new Bird(50, "Happy"); cat.getWeight(); cat.meow(); bird.getWeight(); bird.fly(); animal.getWeight(); } Output: Bela’s weight: 500 Bela meowing Happy’s weight: 50 Happy flying null’s weight: 0

How constructors work in inheritance In Java, constructor of base class with no argument gets automatically called in derived class constructor. class BaseClass { BaseClass() { System.out.println("Base Class Constructor"); } class DerivedClass extends BaseClass { DerivedClass() { System.out.println("Derived Class Constructor");

How constructors work in inheritance In Java, constructor of base class with no argument gets automatically called in derived class constructor. public class TestConstructor { public static void main(String[] args) { DerivedClass dc = new DerivedClass(); } Output: Base Class Constructor Derived Class Constructor

How about parameterised constructors We can call them using super() [already shown in the previous Animal example] In this case base class constructor call must be the first line in derived class constructor class DerivedClass extends BaseClass { int i; DerivedClass(double d, int i) { super(d); this.i=i; } public void display() { System.out.println("d = "+d+", i = "+i); 24 class BaseClass { double d; BaseClass(double d) { this.d = d; } }

How about parameterised constructors We can call them using super() In this case base class constructor call must be the first line in derived class constructor public class TestSuper { public static void main(String[] args) { DerivedClass dc = new DerivedClass(10.25, 20); dc.display(); } Output: d = 10.25, i = 20

Observation(1) class BaseClass { double d; BaseClass(double d) { this.d = d; } ?? class DerivedClass extends BaseClass { } public class TestSuper { public static void main(String[] args) { DerivedClass dc = new DerivedClass(); }

Observation(1) contd. If we specify a constructor explicitly, as in BaseClass, the Java compiler will not create a default constructor for that class. If we don't specify a constructor explicitly, as in DerivedClass, the Java compiler will create a default constructor for that class like this: DerivedClass() { super(); }

Observation(2) Output: ?? class BaseClass { } class DerivedClass extends BaseClass { } Output: ?? public class TestSuper { public static void main(String[] args) { DerivedClass dc = new DerivedClass(); System.out.println("Things are OK"); }

Observation(2) contd. Output: Things are OK class BaseClass { } class DerivedClass extends BaseClass { } Output: Things are OK public class TestSuper { public static void main(String[] args) { DerivedClass dc = new DerivedClass(); System.out.println("Things are OK"); }

Observation (3) Why constructors cannot be inherited? Justify Exercise!

Image source: google 31

Access Modifiers Access Modifier Class or member can be referenced by… public methods of the same class, and methods of other classes private methods of the same class only protected methods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package-access/ package-private) methods in the same package only

public vs. private Classes are usually declared to be public Instance variables are usually declared to be private Methods that will be called by the client of the class are usually declared to be public Methods that will be called only by other methods of the class are usually declared to be private APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class

What You Can Do in a Subclass A subclass inherits all of the public, protected, package-private members of its base You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. And many more….

More use of the super keyword can be used to refer to base class's methods, variables, constructors to call them – needed when there is a name conflict (hiding/shadowing) with current class useful when overriding and you want to keep the old behavior but add new behavior to it syntax: super(args); //call parent’s constructor super.fieldName //access parent’s field super.methodName(args);//access parent’s method

to invoke Parent’s class variable class BaseClass { public int x = 10; } class SubClass extends BaseClass int x = 100; public void display(){ System.out.println(x); public class TestSuper{ public static void main(String args[]){ SubClass s= new SubClass(); s.display(); } Output: ??

to invoke Parent class variable class BaseClass { public int x = 10; } class SubClass extends BaseClass int x = 100; public void Display(){ System.out.println(x); public class TestSuper{ public static void main(String args[]){ SubClass s= new SubClass(); s.Display(); } Output: 100

to invoke Parent’s class variable In the program we have the same variable “x” declared in both base class and sub class A class can declare a variable with the same name as an inherited variable from its parent class, thus "hiding" or shadowing the inherited version referring to the variable by name will use the one closest in scope

to invoke Parent class variable class BaseClass { public int x = 10; } class SubClass extends BaseClass int x = 100; public void display(){ System.out.println(super.x); public class TestSuper{ public static void main(String args[]){ SubClass s= new SubClass(); s.display(); } Output: 10

to invoke Parent class method class SubClass extends BaseClass { public void display(){ System.out.println("Sub class"); } public void print(){ display(); class BaseClass { public void display(){ System.out.println("Base class"); }

to invoke Parent class method public class TestSuper{ public static void main(String args[]){ SubClass s= new SubClass(); s.print(); } Output: ?? }

to invoke Parent class method public class TestSuper{ public static void main(String args[]){ SubClass s= new SubClass(); s.print(); } Output: Sub class } display() method is overridden. The argument list and return type should be exactly the same in both base and sub classes.

to invoke Parent class method class SubClass extends BaseClass { public void display(){ System.out.println("Sub class"); } public void print(){ super.display(); class BaseClass { public void display(){ System.out.println("Base class"); }

to invoke Parent class method public class TestSuper{ public static void main(String args[]){ SubClass s= new SubClass(); s.print(); } Output: Base class }

Overriding Overriding means modifying the implementation of the method with same signature. Subclass can override a method implementation to provide a different version than parent. Subclass can add some information to parent version of the method. Subclass can completely re-define the parent’s method.

Overloading Vs. Overriding Overloading: more than one method in the same class with the same name but different signatures Overriding: same name and same signatures method in the base and sub classes Overloading allows us defining a similar operation in different ways for different data Overriding allows us defining a similar operation in different ways for different object types

Overloading Vs. Overriding Overloading deals with multiple methods in the same class with the same name but different signatures. Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature. Overloading lets you define a similar operation in different ways for different data. Overriding lets you define a similar operation in different ways for different object types.

The Object Class

The Object Class Java defines the class java.lang.Object that is defined as a superclass for all classes All classes directly or indirectly extend the Object class Hence ,all classes inherit Object’s methods.

The Object Class contd. The following two class definitions are equivalent: class A class A extends Object { //code } { //code }

Methods of Object Class The Object class defines a set of methods that are inherited by all classes, including equals(Object o), getClass(), toString() toString() method that is used whenever we want to get a String representation of an object When we define a new class, we can override the toString() method in order to have a suitable representation of the new type of objects as Strings

toString() method Animal Cat Consider the simple example

toString() method public class Animal { int weight; String name; // constructor public Animal(){} public Animal(int weight, String name) { this.weight = weight; this.name = name; } // methods @Override public String toString(){//overriding the toString() method return name+"’s weight: " + weight;

toString() method lass Cat extends Animal { public Cat(int weight, String name) super(weight, name); } public void meow() System.out.println(name+ " meowing");

toString() method class TestAnimal { public static void main(String args[]) { Cat cat = new Cat(500, "Bela"); System.out.println(cat); cat.meow(); } Output: Bela’s weight: 500 Bela meowing

Reference Chapter 11, Introduction to Java Programming, Liang.