Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Similar documents
Chapter 5. Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Chapter 14 Abstract Classes and Interfaces

What is Inheritance?

EKT472: Object Oriented Programming. Overloading and Overriding Method

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

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

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

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

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

CS-202 Introduction to Object Oriented Programming

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

C++ Important Questions with Answers

Lecture 2: Java & Javadoc

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

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Instance Members and Static Members

PROGRAMMING LANGUAGE 2

ITI Introduction to Computing II

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

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

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

Questions Answer Key Questions Answer Key Questions Answer Key

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

ITI Introduction to Computing II

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

Questions Answer Key Questions Answer Key Questions Answer Key

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 9 Inheritance

Inheritance and Polymorphism

CS1150 Principles of Computer Science Objects and Classes

Questions Answer Key Questions Answer Key Questions Answer Key

Inheritance and Polymorphism

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

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

INHERITANCE Mrs. K.M. Sanghavi

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

CS 251 Intermediate Programming Inheritance

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

Inheritance (continued) Inheritance

Class, Variable, Constructor, Object, Method Questions

Inheritance and Polymorphism

CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism

Method Overriding in Java

What are the characteristics of Object Oriented programming language?

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Practice for Chapter 11

Inheritance (an intuitive description)

Java Fundamentals (II)

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Object Oriented Programming. Java-Lecture 11 Polymorphism

More Relationships Between Classes

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

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

Object Orientated Programming Details COMP360

Computer Science 210: Data Structures

Inheritance (Outsource: )

Basics of Object Oriented Programming. Visit for more.

ECE 122. Engineering Problem Solving with Java

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Unit 4 - Inheritance, Packages & Interfaces

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Chapter 5 Object-Oriented Programming

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

JAVA. Lab-9 : Inheritance

Example: Count of Points

Computer Science II (20073) Week 1: Review and Inheritance

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Java Magistère BFA

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

Lecture Notes Chapter #9_b Inheritance & Polymorphism

CS260 Intro to Java & Android 03.Java Language Basics

CS1020: DATA STRUCTURES AND ALGORITHMS I

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

index.pdf January 21,

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Inheritance -- Introduction

1 Shyam sir JAVA Notes

ITI Introduction to Computing II

Starting Out with Java: From Control Structures Through Objects Sixth Edition

25. Generic Programming

ITI Introduction to Computing II

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Chapter 6 Introduction to Defining Classes

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

[ L5P1] Object-Oriented Programming: Advanced Concepts

Object-Oriented Concepts

Making New instances of Classes

Transcription:

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Chapter 5 Inheritance

Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super and final Understand the basics of abstract class.

Inheritance Is the ability to derive something specific from something generic. aids in the reuse of code. A class can inherit the features of another class and add its own modification. The parent class is the super class and the child class is known as the subclass. A subclass inherits all the properties and methods of the super class.

Inheritance

Aggregation We can make up objects out of other objects. The behaviour of the bigger object is defined by the behaviour of its component objects, separately and in conjunction with each other. cars contain engine which in turn contains an ignition system and starter motor. a whole-part relationship exists in aggregation car being the whole and engine being its part.

Types of Inheritance Single Multiple Multilevel Hierarchical Hybrid

Single level inheritance Classes have only base class

Multi level There is no limit to this chain of inheritance (as shown below) but getting down deeper to four or five levels makes code excessively complex.

Multiple Inheritance A class can inherit from more than one unrelated class

Hierarchical Inheritance In hierarchical inheritance, more than one class can inherit from a single class. Class C inherits from both A and B.

Hybrid Inheritance is any combination of the above defined inheritances

Deriving Classes Classes are inherited from other class by declaring them as a part of its definition For e.g. class MySubClass extends MySuperClass extends keyword declares that MySubClass inherits the parent class MySuperClass.

Inheritance

Method Overriding a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. it is a feature that supports polymorphism. When an overridden method is called through the subclass object, it will always refer to the version of the method defined by the subclass. The superclass version of the method is hidden.

Method Overriding Example class A { int i = 0; void dooverride (int k) { i = k; } } class B extends A { void dooverride(int k) { i = 2 * k; System.out.println( The value of i is: +i); } public static void main (String args[]) { B b = new B(); b.dooverride(12); }}

The output The value of i is: 24

Late binding Vs Early binding Binding is connecting a method call to a method body. When binding is performed before the program is executed, it is called early binding. If binding is delayed till runtime it is late binding. also known as dynamic binding or runtime binding. All the methods in Java use late binding (except static and final).

Superclass Can Refer to a Subclass class SuperClass { Object int instancevariable = 10; static int classvariable = 20;} class SubClass extends SuperClass{ int instancevariable = 12; static int classvariable = 25; public static void main(string args[]) { SuperClass s=new SubClass();

Superclass Can Refer to a Subclass Object System.out.println("Superclass Instance variable: "+s.instancevariable); System.out.println("Superclass static variable: "+s.classvariable); SubClass st=new SubClass(); System.out.println("Subclass Instance variable: "+st.instancevariable); System.out.println("Subclass static variable: "+st.classvariable); } }

The Output Superclass Instance variable: 10 Superclass static variable: 20 Subclass Instance variable: 12 Subclass static variable: 25

super Keyword For invoking the methods of the super class. For accessing the member variables of the super class. For invoking the constructors of the super class.

super Keyword (contd.) class A { void show() { System.out.println( Super Class show method ); } } class B extends A void show() { System.out.println( Subclass show method ); } public static void main (String args[ ]) { A s1=new A(); s1.show(); B s2=new B (); s2.show(); }}

Problem and Solution Two methods being called by two different objects (inherited), instead the job can be done by one object only, i.e. using super keyword.

Case 1: Invoking Methods using super class ANew { void show() { System.out.println( Super Class show method ); } } class BNew extends ANew { void show() { super.show(); System.out.println( Subclass show method ); } public static void main (String args[ ]) { BNew s2=new BNew (); s2.show(); }}

Case 2: Accessing variables using super class Super_Variable { int b=30; } class SuperClass extends Super_Variable { int b=12; void show() { System.out.println( subclass class variable: + b); System.out.println( superclass instance variable: + super.b); } public static void main (String args[]) { SuperClass s=new SubClass(); s.show(); // call to show method of Sub Class B }}

The output subclass class variable: 12 superclass instance variable: 30

Case 3: constructors of the super class. class Constructor_A { Constructor_A() { System.out.println( Constructor A ); }} class Constructor_B extends Constructor_A { Constructor_B() { System.out.println( Constructor B ); }} class Constructor_C extends Constructor_B { Constructor_C() { System.out.println( Constructor C ); } public static void main (String args[]) { Constructor_C a=new Constructor_C(); }}

The Output Constructor A Constructor B Constructor C

Case 3: (contd.) class Constructor_A_Revised { Constructor_A_Revised() { System.out.println( Constructor A Revised ); }} class Constructor_B_Revised extends Constructor_A_Revised { /*Constructor_B_Revised() { System.out.println( Constructor B ); }*/ Constructor_B_Revised(int a) { a++; System.out.println( Constructor B Revised + a ); }} class Constructor_C_Revised extends Constructor_B_Revised { Constructor_C_Revised() { super(11); // if omitted compile time error results System.out.println( Constructor C Revised ); } public static void main (String args[]) { Constructor_C_Revised a=new Constructor_C_Revised(); }}

The Output Constructor A Revised Constructor B Revised 12 Constructor C Revised

final keyword Declaring constants (used with variable and argument declaration) final int MAX=100; Disallowing method overriding (used with method declaration) final void show (final int x) Disallowing inheritance (used with class declaration). final class Demo {}

Your Turn What is method overriding? Highlight the usage of super keyword? What are the usages of final keyword? What is late binding and early binding?

Abstract class Abstract classes are classes with a generic concept, not related to a specific class. Abstract classes define partial behaviour and leave the rest for the subclasses to provide. contain one or more abstract methods. abstract method contains no implementation, i.e. no body. Abstract classes cannot be instantiated, but they can have reference variable. If the subclasses does not override the abstract methods of the abstract class, then it is mandatory for the subclasses to tag itself as abstract.

Why create abstract methods? to force same name and signature pattern in all the subclasses subclasses should not use their own naming patterns They should have the flexibility to code these methods with their own specific requirements.

Example of Abstract class abstract class Animal { String name; String species; Animal(String n, String s) { name=n; species=s; } void eat(string fooditem) { System.out.println(species + + name + likes to have + fooditem); } abstract void sound(); }

Shadowing Vs Overriding Shadowing of fields occurs when variable names are same. It may occur when local variables and instance variable names collide within a class or variable names in superclass and subclass are same. In case of methods, instance methods are overridden whereas static methods are shadowed. The difference between the two is important because shadowed methods are bound early whereas instance methods are dynamically (late) bound.

Shadowing Vs Overriding class Shadowing{ static void display(){ System.out.println("In Static Method of Superclass"); } void instancemethod() { System.out.println("In instance Method of Super Class"); }}

Shadowing Vs Overriding class ShadowingTest extends Shadowing { static void display(){ System.out.println("In Static Method of Sub Class"); } void instancemethod() { System.out.println("The Overridden instance Method in Sub Class"); }

Shadowing Vs Overriding public static void main(string args[]){ Shadowing s=new ShadowingTest(); s.display(); s.instancemethod(); ShadowingTest st=new ShadowingTest(); st.display(); st.instancemethod(); } }

The Output In Static Method of Superclass The Overridden instance Method in Subclass In Static Method of Subclass The Overridden instance Method in Subclass

Practical Problem: Circle class class Circle { float radius; final fl oat PI = 3.141f; //value of pi is fi xed Circle(){ radius = 1.0f;} Circle(fl oat radius) { this.radius = radius;} float getarea() { return PI * radius * radius; }}

Practical problem: Cylinder class class Cylinder extends Circle { float height; Cylinder(fl oat radius, fl oat height){ super(radius); this.height = height; } float getarea() { return 2 * super.getarea() + 2 * PI * radius * height; }

Practical problem public static void main(string args[]) { Circle c = new Circle(1.5f); System.out.println("The Area of Circle is: " + c.getarea()); Cylinder cy = new Cylinder(1.5f,3.5f); System.out.println("The Surface Area of Cylinder is: " + cy.getarea()); }}

Summary The concept of Inheritance is derived from real life. The properties and methods of a parent class are inherited by the children or subclasses. Subclasses can provide new implementation of method using method overriding, keeping the method names and signatures same as that of the parent class. The super keyword can be used to access the overridden methods, variables and even the constructors of the super class. Abstract classes are used to force the subclasses to override abstract methods and provide body and code for them. The final keyword is used to create constants and disallow inheritance.