INHERITANCE Mrs. K.M. Sanghavi

Similar documents
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Answer1. Features of Java

Java static keyword static keyword

Chapter 5. Inheritance

Create a Java project named week10

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

this keyword in java javatpoint

Fundamentals of Object Oriented Programming

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

OVERRIDING. 7/11/2015 Budditha Hettige 82

Method Overriding in Java

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Unit 4 - Inheritance, Packages & Interfaces

Inheritance and Polymorphism

K.Yellaswamy Assistant Professor CMR College of Engineering & Technology

Java Object Oriented Design. CSC207 Fall 2014

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

What is Inheritance?

SRI VIDYA COLLEGE OF ENGG & TECH UNIT -2 INHERITANCE AND INTERFACES SVCET

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

What are the characteristics of Object Oriented programming language?

INHERITANCE. Spring 2019

COLLEGE OF ENGINEERING, NASHIK

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Inheritance. Transitivity

Inheritance and Polymorphism

Abstract class & Interface

Chapter 14 Abstract Classes and Interfaces

Inheritance, and Polymorphism.

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Accelerating Information Technology Innovation

PROGRAMMING LANGUAGE 2

Object Oriented Programming. Java-Lecture 11 Polymorphism

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

CS-202 Introduction to Object Oriented Programming

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

1 - Basics of Java. Explain features of JAVA.

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

CS8392 /Object Oriented Programming

Basics of Object Oriented Programming FCITR MAGAZINE DR. SHAKEEL AHMAD

Inheritance (Outsource: )

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Instance Members and Static Members

More Relationships Between Classes

Inheritance Motivation

Exercise: Singleton 1

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

Data Structures (list, dictionary, tuples, sets, strings)

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

First IS-A Relationship: Inheritance

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Inheritance & Polymorphism

OOP in Java Review. CS356 Object-Oriented Design and Programming October 1, 2014

Classes and Inheritance Extending Classes, Chapter 5.2

Inheritance and Interfaces

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Questions Answer Key Questions Answer Key Questions Answer Key

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Object Orientated Programming Details COMP360

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Example: Count of Points

Subclasses, Superclasses, and Inheritance

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Chapter 5 Object-Oriented Programming

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

Questions Answer Key Questions Answer Key Questions Answer Key

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Arrays Classes & Methods, Inheritance

Java Fundamentals (II)

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

QUESTIONS FOR AVERAGE BLOOMERS

Object-Oriented Programming

Lesson 10. Work with Interfaces and Abstract Classes. Copyright all rights reserved

Inheritance, polymorphism, interfaces

Object Oriented Java

Programming in C# Inheritance and Polymorphism

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

CS313D: ADVANCED PROGRAMMING LANGUAGE

JAVA MOCK TEST JAVA MOCK TEST II

CS 251 Intermediate Programming Inheritance

Inheritance -- Introduction

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Crash Course Review Only. Please use online Jasmit Singh 2

Transcription:

INHERITANCE Mrs. K.M. Sanghavi

Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship.

Use of inheritance in java For Method Overriding (so runtime polymorphism can be achieved). For Code Reusability.

Syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called parent or super class and the new class is called child or subclass.

Java Inheritance Example As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

Java Inheritance Example class Employee{ float salary=40000; class Programmer extends Employee{ int bonus=10000; public static void main(string args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); Output : Programmer salary is:40000.0 Bonus of programmer is:10000

Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Single Inheritance Example class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void bark(){system.out.println("barking..."); class TestInheritance{ public static void main(string args[]){ Dog d=new Dog(); d.bark(); d.eat(); Output: barking... eating...

class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void bark(){system.out.println("barking..."); Multilevel Inheritance Example class BabyDog extends Dog{ void weep(){system.out.println("weeping...");

class TestInheritance2{ public static void main(string args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); Output: Multilevel Inheritance Example weeping... barking... eating...

Hierarchical Inheritance Example class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void bark(){system.out.println("barking..."); class Cat extends Animal{ void meow(){system.out.println("meowing...");

Hierarchical Inheritance Example class TestInheritance3{ public static void main(string args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//c.t.error Output: meowing... eating...

Method Overriding in Java If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding Method overriding is used to provide specific implementation of a method that is already provided by its super class. Method overriding is used for runtime polymorphism

Rules for Java Method Overriding method must have same name as in the parent class method must have same parameter as in the parent class. must be IS-A relationship (inheritance).

Example of method overriding In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding. class Vehicle{ void run(){system.out.println("vehicle is running");

Example of method overriding class Bike2 extends Vehicle{ void run(){system.out.println("bike is running safely"); public static void main(string args[]){ Bike2 obj = new Bike2(); obj.run();

super keyword in java The super keyword in java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

super keyword in java 1. super can be used to refer immediate parent class instance variable. 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor.

super : used to invoke immediate parent class instance variable. class Animal{ String color="white"; class Dog extends Animal{ String color="black"; void printcolor(){ System.out.println(color);//prints color of Dog class System.out.println(super.color);//prints color of Animal class class TestSuper1{ public static void main(string args[]){ Dog d=new Dog(); d.printcolor(); Output: black white

super : used to refer immediate parent class method. class Animal{ void eat(){system.out.println("eating..."); class Dog extends Animal{ void eat(){system.out.println("eating bread..."); void bark(){system.out.println("barking..."); void work() { super.eat(); bark(); class TestSuper2{ public static void main(string args[]){ Dog d=new Dog(); d.work(); Output: eating... barking...

super : used to invoke immediate parent class conctructor. class Animal{ Animal(){System.out.println("animal is created"); class Dog extends Animal{ Dog(){ super(); Output System.out.println("dog is created"); class TestSuper3{ public static void main(string args[]){ Dog d=new Dog(); animal is created dog is created

Another super example class Person{ int id; String name; Person(int id,string name){ this.id=id; this.name=name;

Another super example continued class Emp extends Person{ float salary; Emp(int id,string name,float salary) { super(id,name);//reusing parent constructor this.salary=salary; void display(){system.out.println(id+" "+name+" "+salary);

Another super example continued class TestSuper5{ public static void main(string[] args) { Emp e1=new Emp(1,"ankit",45000f); e1.display(); Output: 1 ankit 45000

Final Keyword In Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class

Final Keyword In Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method Class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.

Java final variable If you make any variable as final, you cannot change the value of final variable(it will be constant). class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; public static void main(string args[]){ Bike9 obj=new Bike9(); obj.run(); //end of class Output:Compile Time Error

Java final method If you make any method as final, you cannot override it. Example of final method class Bike{ final void run(){system.out.println("running"); class Honda extends Bike{ void run(){system.out.println("running safely with 100kmph"); //Error public static void main(string args[]){ Honda honda= new Honda(); honda.run(); Output: Compile Time Error

Java final class If you make any class as final, you cannot extend it. Example final class Bike{ class Honda1 extends Bike{ //Error void run(){system.out.println("running safely with 100kmph"); public static void main(string args[]){ Honda1 honda= new Honda(); honda.run(); Output:Compile Time Error

Blank or uninitialized final variable A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor.

Example of blank final variable class Student{ int id; String name; final String PAN_CARD_NUMBER;...

Dynamic Method Dispatch Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Upcasting When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example: class A{ class B extends A{ A a=new B();//upcasting

Dynamic Method Dispatch Example class Bank{ float getrateofinterest(){return 0; class SBI extends Bank{ float getrateofinterest(){return 8.4f; class ICICI extends Bank{ float getrateofinterest(){return 7.3f; class AXIS extends Bank{ float getrateofinterest(){return 9.7f;

Dynamic Method Dispatch Example class TestPolymorphism{ public static void main(string args[]){ Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getrateofinterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getrateofinterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getrateofinterest());

Abstractionin Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. Ways to achieve Abstaction There are two ways to achieve abstraction in java Abstract class (0 to 100%) Interface (100%)

Abstract class in Java A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body). It needs to be extended and its method implemented. It cannot be instantiated.

Abstract class in Java abstract class Shape{ abstract void draw(); //In real scenario, implementation is provided by others i.e. unk //nown by end user class Rectangle extends Shape{ void draw(){system.out.println("drawing rectangle"); class Circle1 extends Shape{ void draw(){system.out.println("drawing circle");

Abstract class in Java //In real scenario, method is called by programmer or u //ser class TestAbstraction1{ public static void main(string args[]){ Shape s=new Circle1();//In real scenario, object is provi //ded through method e.g. getshape() method s.draw();

Interface in Java An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java. Java Interface also represents IS-A relationship. It cannot be instantiated just like abstract class.

Why use Java interface? There are mainly three reasons to use interface. They are given below. It is used to achieve abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.

Relationship between classes and interfaces As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.

Java Interface Example In this example, Printable interface has only one method, its implementation is provided in the A class. interface printable{ void print(); class A implements printable{ public void print(){system.out.println("hello"); public static void main(string args[]){ A obj = new A(); obj.print();

Java Interface Example2 //Interface declaration: by first user interface Drawable{ void draw(); //Implementation: by second user class Rectangle implements Drawable{ public void draw(){system.out.println("drawing rectangle"); class Circle implements Drawable{ public void draw(){system.out.println("drawing circle");

Java Interface Example2 continued //Using interface: by third user class TestInterface1{ public static void main(string args[]){ Drawable d=new Circle(); //In real scenario, object is provided //by method e.g. getdrawable() d.draw();

Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

class A{ void msg(){system.out.println("hello"); class B{ void msg(){system.out.println("welcome"); class C extends A,B{//suppose if it were public static void main(string args[]){ C obj=new C(); obj.msg();//now which msg() method would be invoked? Output : Compile Time Error

Multiple Inheritance in Java If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

Multiple Inheritance in Java interface Printable{ void print(); interface Showable{ void show(); class A implements Printable, Showable{ public void print(){system.out.println("hello"); public void show(){system.out.println("welcome"); public static void main(string args[]){ A obj = new A (); obj.print(); obj.show();

Interface inheritance A class implements interface but one interface extends another interface interface Printable{ void print(); interface Showable extends Printable{ void show(); class TestInterface4 implements Showable{ public void print(){system.out.println("hello"); public void show(){system.out.println("welcome"); public static void main(string args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show();

Difference between abstract class and interface Abstract class 1) Abstract class can have abstract and non-abstract methods. 2) Abstract class doesn't support multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. 4) Abstract class can provide the implementation of interface. 5) The abstract keyword is used to declare abstract class. 6) Example: public abstract class Shape{ public abstract void draw(); Interface Interface can have only abstract methods. Since Java 8, it can have default and static methods also. Interface supports multiple inheritance. Interface has only static and final variables. Interface can't provide the implementation of abstract class. The interface keyword is used to declare interface. Example: public interface Drawable{ void draw();