SlideShare a Scribd company logo
1 of 40
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.
08/25/16
Student – Base class
Rollno, name, 6 marks
NCCStudent extends Student
Placement extends Student
PlacementId, Placementfee
Internship extends Placement
Typeofinternship, duration
Rollno,
name,
6 marks
Rollno,
name,
6 marks +
PlacementId,
Placementfee
Rollno,
name,
6 marks
PlacementId,
Placementfee
Typeofinternship,
duration
08/25/16
StudentAll
Rollno,
name,
6 marks
PlacementId,
Placementfee
Typeofinternship,
Duration
100 objects – how many fields -12
12 fields filled up - 2
10 fields filled up - 20
8 fields filled up – 80
Multiple Inheritance
A class can inherit from more than one unrelated
class
C extends A,B
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.
Superclass Can Refer to a Subclass
Object
The real power of overriding is illustrated by the
following code. A super class reference
variable can be assigned a subclass object.
E.g. in the example of method overriding we can
create an object of class A by referring
subclass B as follows,
AClass a = new BClass();
a.doOverride();
super Keyword
The “super” keyword refers to the parent class
of the class in which the keyword is used. It is
used for following three purposes,
• For calling 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(“Sub Class show method”);
}
public static void main (String args[ ])
{
A s1=new A();
s1.show();
B s2=new B ();
s2.show();
}
}
Problem and Solution
• o/p=> Super Class show method
Sub Class show method
• Two methods show() and overridden show()
are being called by two different objects A and
B , instead the job can be done by one object
only, i.e. using super keyword.
Case 1: Invoking Methods using super
import java.io.*;
class Anew
{
void show()
{
System.out.println(“Super Class show method”);
}
}
class BNew extends Anew
{
void show()
{
super.show();
System.out.println(“Sub Class show method”);
}
public static void main (String args[ ])
{
BNew s2=new BNew ();
s2.show();
}
}
OUTPUT
• => Super Class show method
Sub Class show method
Case 2: Accessing variables using super
import java.io.*;
class Super_Variable
{
int b=30;
}
class Sub_Class 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[])
{
Sub_Class s=new Sub_Class();
s.show();
}
}
The output
• subclass class variable: 12
• superclass instance variable: 30
Case 3: constructors of the super class.
import java.io.*;
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 c=new Constructor_C();
}
}
The Output
Constructor A
Constructor B
Constructor C
Case 3: (contd.)
import java.io.*;
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);
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)
– E.g. final int MAX=100;
• Disallowing method overriding (used with method
declaration)
– final void show (final int x)
{
// statements
}
• Disallowing inheritance (used with class declaration).
– final class Demo
{
//statements
}
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?
© Oxford University Press 2013. All rights reserved.
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.
© Oxford University Press 2013. All rights reserved.
Need of creating abstract method
• 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.
© Oxford University Press 2013. All rights reserved.
Example of Abstract class
abstract class Animal
{
String name;
String species;
void AnimalName(String n)
{
name=n;
System.out.println("Animal is "+name);
}
void AnimalEat(String fooditem)
{
System.out.println(name + " likes to have "+ fooditem);
}
abstract void AnimalSound(String sound);
}
class Lion extends Animal
{
void AnimalSound(String sound)
{
System.out.println(name+" always "+sound);
}
public static void main(String args[])
{
Lion a=new Lion();
a.AnimalName("Lion");
a.AnimalEat("meat");
a.AnimalSound("Roar");
}
}
© Oxford University Press 2013. All rights reserved.
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; }}
© Oxford University Press 2013. All rights reserved.
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; }
© Oxford University Press 2013. All rights reserved.
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());
}}
© Oxford University Press 2013. All rights reserved.
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.
© Oxford University Press 2013. All rights reserved.
• Q.1 what will happen when you run the following code.
class Demo
{
Demo(int i)
{
System.out.println(“Demo”);
}
}
class InnerClass extends Demo
{
public static void main(String args[])
{
InnerClass s=new InnerClass();
}
void InnerClass()
{
System.out.println(“Inner Class”);
}
}
© Oxford University Press 2013. All rights reserved.
a) Compilation and output of string is “Inner Class ” at
run time.
b) Compile time error
c) Compilation and no output at run time.
d) Compilation and output of string is “Demo”

More Related Content

What's hot

6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception HandlingNilesh Dalvi
 
Object oriented concepts with java
Object oriented concepts with javaObject oriented concepts with java
Object oriented concepts with javaishmecse13
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and IntefacesNilesh Dalvi
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Polymorphism
PolymorphismPolymorphism
PolymorphismNuha Noor
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 

What's hot (15)

Cs8392 oops 5 units notes
Cs8392 oops 5 units notes Cs8392 oops 5 units notes
Cs8392 oops 5 units notes
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
Core java
Core javaCore java
Core java
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Object oriented concepts with java
Object oriented concepts with javaObject oriented concepts with java
Object oriented concepts with java
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Unit 4
Unit 4Unit 4
Unit 4
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Packages
PackagesPackages
Packages
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 

Similar to Ch5 inheritance

Similar to Ch5 inheritance (20)

L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
Unit 7 inheritance
Unit 7 inheritanceUnit 7 inheritance
Unit 7 inheritance
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
 
Chap11
Chap11Chap11
Chap11
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 

More from HarshithaAllu

Environmenal protection
Environmenal protectionEnvironmenal protection
Environmenal protectionHarshithaAllu
 
Social project work-political parties
Social project work-political partiesSocial project work-political parties
Social project work-political partiesHarshithaAllu
 
ROLE OF PRINT MEDIA IN FREEDOM STRUGGLE
ROLE OF PRINT MEDIA IN FREEDOM STRUGGLEROLE OF PRINT MEDIA IN FREEDOM STRUGGLE
ROLE OF PRINT MEDIA IN FREEDOM STRUGGLEHarshithaAllu
 
java programming - applets
java programming - appletsjava programming - applets
java programming - appletsHarshithaAllu
 
PRAGRAMMING IN JAVA (BEGINNER)
PRAGRAMMING IN JAVA (BEGINNER)PRAGRAMMING IN JAVA (BEGINNER)
PRAGRAMMING IN JAVA (BEGINNER)HarshithaAllu
 
Hyper text transport protocol
Hyper text transport protocolHyper text transport protocol
Hyper text transport protocolHarshithaAllu
 
PRESSENTATION SKILLS
PRESSENTATION SKILLSPRESSENTATION SKILLS
PRESSENTATION SKILLSHarshithaAllu
 
IR remote sensing technology
IR remote sensing technologyIR remote sensing technology
IR remote sensing technologyHarshithaAllu
 
Closed loop (automated) insulin delivery
Closed loop (automated) insulin delivery Closed loop (automated) insulin delivery
Closed loop (automated) insulin delivery HarshithaAllu
 

More from HarshithaAllu (11)

Environmenal protection
Environmenal protectionEnvironmenal protection
Environmenal protection
 
Social project work-political parties
Social project work-political partiesSocial project work-political parties
Social project work-political parties
 
ROLE OF PRINT MEDIA IN FREEDOM STRUGGLE
ROLE OF PRINT MEDIA IN FREEDOM STRUGGLEROLE OF PRINT MEDIA IN FREEDOM STRUGGLE
ROLE OF PRINT MEDIA IN FREEDOM STRUGGLE
 
Operating system
Operating systemOperating system
Operating system
 
java programming - applets
java programming - appletsjava programming - applets
java programming - applets
 
PRAGRAMMING IN JAVA (BEGINNER)
PRAGRAMMING IN JAVA (BEGINNER)PRAGRAMMING IN JAVA (BEGINNER)
PRAGRAMMING IN JAVA (BEGINNER)
 
Structure of neuron
Structure of neuronStructure of neuron
Structure of neuron
 
Hyper text transport protocol
Hyper text transport protocolHyper text transport protocol
Hyper text transport protocol
 
PRESSENTATION SKILLS
PRESSENTATION SKILLSPRESSENTATION SKILLS
PRESSENTATION SKILLS
 
IR remote sensing technology
IR remote sensing technologyIR remote sensing technology
IR remote sensing technology
 
Closed loop (automated) insulin delivery
Closed loop (automated) insulin delivery Closed loop (automated) insulin delivery
Closed loop (automated) insulin delivery
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 

Ch5 inheritance

  • 1. Programming in Java, 2e Sachin Malhotra Saurabh Choudhary
  • 3. 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.
  • 4. 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.
  • 6. 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.
  • 7. Types of Inheritance • Single • Multiple • Multilevel • Hierarchical • Hybrid
  • 8. Single level inheritance Classes have only base class
  • 9. 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.
  • 10. 08/25/16 Student – Base class Rollno, name, 6 marks NCCStudent extends Student Placement extends Student PlacementId, Placementfee Internship extends Placement Typeofinternship, duration Rollno, name, 6 marks Rollno, name, 6 marks + PlacementId, Placementfee Rollno, name, 6 marks PlacementId, Placementfee Typeofinternship, duration
  • 11. 08/25/16 StudentAll Rollno, name, 6 marks PlacementId, Placementfee Typeofinternship, Duration 100 objects – how many fields -12 12 fields filled up - 2 10 fields filled up - 20 8 fields filled up – 80
  • 12. Multiple Inheritance A class can inherit from more than one unrelated class C extends A,B
  • 13. Hierarchical Inheritance • In hierarchical inheritance, more than one class can inherit from a single class. Class C inherits from both A and B.
  • 14. Hybrid Inheritance • is any combination of the above defined inheritances
  • 15. 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.
  • 17. 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.
  • 18. Superclass Can Refer to a Subclass Object The real power of overriding is illustrated by the following code. A super class reference variable can be assigned a subclass object. E.g. in the example of method overriding we can create an object of class A by referring subclass B as follows, AClass a = new BClass(); a.doOverride();
  • 19. super Keyword The “super” keyword refers to the parent class of the class in which the keyword is used. It is used for following three purposes, • For calling the methods of the super class. • For accessing the member variables of the super class. • For invoking the constructors of the super class.
  • 20. super Keyword (contd.) class A { void show() { System.out.println(“Super Class show method”); } } class B extends A { void show() { System.out.println(“Sub Class show method”); } public static void main (String args[ ]) { A s1=new A(); s1.show(); B s2=new B (); s2.show(); } }
  • 21. Problem and Solution • o/p=> Super Class show method Sub Class show method • Two methods show() and overridden show() are being called by two different objects A and B , instead the job can be done by one object only, i.e. using super keyword.
  • 22. Case 1: Invoking Methods using super import java.io.*; class Anew { void show() { System.out.println(“Super Class show method”); } } class BNew extends Anew { void show() { super.show(); System.out.println(“Sub Class show method”); } public static void main (String args[ ]) { BNew s2=new BNew (); s2.show(); } }
  • 23. OUTPUT • => Super Class show method Sub Class show method
  • 24. Case 2: Accessing variables using super import java.io.*; class Super_Variable { int b=30; } class Sub_Class 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[]) { Sub_Class s=new Sub_Class(); s.show(); } }
  • 25. The output • subclass class variable: 12 • superclass instance variable: 30
  • 26. Case 3: constructors of the super class. import java.io.*; 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 c=new Constructor_C(); } }
  • 28. Case 3: (contd.) import java.io.*; 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); System.out.println("Constructor C Revised"); } public static void main (String args[]) { Constructor_C_Revised a=new Constructor_C_Revised(); } }
  • 29. The Output Constructor A Revised Constructor B Revised 12 Constructor C Revised
  • 30. final keyword • Declaring constants (used with variable and argument declaration) – E.g. final int MAX=100; • Disallowing method overriding (used with method declaration) – final void show (final int x) { // statements } • Disallowing inheritance (used with class declaration). – final class Demo { //statements }
  • 31. 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?
  • 32. © Oxford University Press 2013. All rights reserved. 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.
  • 33. © Oxford University Press 2013. All rights reserved. Need of creating abstract method • 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.
  • 34. © Oxford University Press 2013. All rights reserved. Example of Abstract class abstract class Animal { String name; String species; void AnimalName(String n) { name=n; System.out.println("Animal is "+name); } void AnimalEat(String fooditem) { System.out.println(name + " likes to have "+ fooditem); } abstract void AnimalSound(String sound); } class Lion extends Animal { void AnimalSound(String sound) { System.out.println(name+" always "+sound); } public static void main(String args[]) { Lion a=new Lion(); a.AnimalName("Lion"); a.AnimalEat("meat"); a.AnimalSound("Roar"); } }
  • 35. © Oxford University Press 2013. All rights reserved. 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; }}
  • 36. © Oxford University Press 2013. All rights reserved. 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; }
  • 37. © Oxford University Press 2013. All rights reserved. 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()); }}
  • 38. © Oxford University Press 2013. All rights reserved. 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.
  • 39. © Oxford University Press 2013. All rights reserved. • Q.1 what will happen when you run the following code. class Demo { Demo(int i) { System.out.println(“Demo”); } } class InnerClass extends Demo { public static void main(String args[]) { InnerClass s=new InnerClass(); } void InnerClass() { System.out.println(“Inner Class”); } }
  • 40. © Oxford University Press 2013. All rights reserved. a) Compilation and output of string is “Inner Class ” at run time. b) Compile time error c) Compilation and no output at run time. d) Compilation and output of string is “Demo”