SlideShare una empresa de Scribd logo
1 de 25
Java Programming
Manish Kumar
(manish87it@gmail.com)
Lecture- 6
Contents
 Introduction to Inheritance
 Importance of Inheritance & Sample code
 Types of Inheritance
 Aggregation in java
 Method Overriding
 Rules for Method Overriding
 Constructor in Inheritance
 Static and Dynamic Binding
inheritance
 Inheritance is a mechanism in java by which one class object is allow to inherit the features i.e. fields &
methods of another class object.
 The class whose features are inherited is called parent/base/super class and the class that inherits the features
is called child/sub/derived class.
 Inheritance in java represents the IS-A relationship which is also called parent-child relationship.
 We used extends keyword to inherit the features of a class. Following is the syntax of extends keyword:
class Child-class extends Parent-class {
// methods;
}
Importance of Inheritance
Method Overriding – We can achieved run-time polymorphism
Code Reusability – Inheritance support the concept Reusability, i.e. you can reuse the fields & methods of the
existing class into new created class.
Sample Code
class Employee{
float salary=40000;
}
class Developer extends Employee{
int bonus=10000;
public static void main(String args[]){
Developer d=new Developer ();
System.out.println("Programmer salary is:"+d.salary);
System.out.println("Bonus of Programmer is:"+d.bonus);
}
}
Output - Programmer salary is: 40000.0
Bonus of programmer is: 10000
Employee.java
In this code, Developer object can access
the field of own class as well as of
Employee class, i.e. code reusability.
As we seeing in this code, Developer is the
child class and Employee is the parent
class. The relationship between the classes
is Developer IS-A Employee. It means that
Developer is a type of Employee.
Types of inheritance
Single
Inheritance
Multilevel
Inheritance
Hierarchal
Inheritance
Multiple
Inheritance
Hybrid
Inheritance
Single inheritance
In single inheritance, one sub-class and one-super-
class.
Super-class
Sub-class
// Test.java
class Demo {
void display() {
System.out.println(“Sparsh Globe”);
}
}
class Test extends Demo {
public static void main(String args[]) {
Demo d = new Demo();
d.display();
}
}
Output - Sparsh Globe
In this example, we can see that Test class inherit the
features of Demo class, so there is a single inheritance.
Multilevel inheritance
When there is a chain of inheritance is called Multilevel
Inheritance, i.e. when a derived class act as the parent class
to other class.
//Main.java
class First {
void show1() {
System.out.println(“S. Globe”);
}
}
Class Second extends First {
void show2() {
System.out.println(“Sparsh Globe”);
}
}
class Third extends Second {
void show3() {
System.out.println(“Third Class”);
}
}
class Main {
public static void main(String args[]) {
Third t = new Third();
t.show1(); t.show2(); t.show3();
}
}
Output - S. Globe
Sparsh Globe
Third Class
A
B
C
Hierarchal inheritance
A single class can inherited by two or more than two class,
known as Hierarchal Inheritance. A
AAA
// Test.java
class First {
void show1() {
System.out.println("S. Globe");
}
}
class Second extends First {
void show2() {
System.out.println("Sparsh Globe");
}
}
class Third extends First {
void show3() {
System.out.println("Third Class");
}
}
class Test {
public static void main(String args[]) {
Third t = new Third();
t.show1(); t.show3();
Second s = new Second();
s.show2();
}
}
Output - S. Globe
Third Class
Sparsh Globe
Multiple inheritance
In this, there are two or more than two parent class exist. That is, one subclass can have two or more than two
parent class. Multiple Inheritance does not supported in java.
A
C
B
In Java, we can achieve multiple inheritance only through interfaces. To reduce the complexity, multiple
inheritance does not support in java.
Multiple & hybrid inheritance
Multiple inheritance is not supported in java. Let’s understand this with a scenario as discussed below:
For Example - 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 the same method and you call it from child class object, there will be ambiguity to call the
method of A or B class.
Hybrid Inheritance - It is a mix of two or more of the above types of inheritance. Since java doesn’t support
multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can
achieve hybrid inheritance only through Interfaces.
aggregation
Aggregation represents HAS-A relationship and if a class have an entity reference, it is known as Aggregation.
Let’s consider an example; suppose a Circle object contains one more object named Operation, which contains
its operation like square, area, etc.
Example –
class Circle {
double pi = 3.14;
Operation op; // Operation is a
class
}
In such case Circle has an entity reference op, so relationship is Circle HAS-A op.
Aggregation (contd..)
Aggregation is used for Code Reusability. Inheritance should be used only if the relationship is-a is maintained
throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.
Example -
//Address.java
public class Address {
String city,state,country;
public Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
aggregation
//Emp.java
public class Emp {
int id;
String name;
Address address;
public Emp(int id, String name,Address address) {
this.id = id;
this.name = name;
this.address=address;
}
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "
+address.country);
}
public static void main(String[] args) {
Address address1=new Address("KNP","UP","india");
Address address2=new Address("LKO","UP","india");
Emp e=new Emp(101,"Manish",address1);
Emp e2=new Emp(102,"Sparsh",address2);
e.display();
e2.display();
}
}
Output –
101 Manish
KNP UP India
102 Sparsh
LKO UP India
Method overriding
Overriding is a concept in which a sub-class to provide a specific implementation of a method that is already
provided by one of its super-class. In this concept, sub-class has a method with same name,
parameter/signature and return type as contains in super-class. In this case we say that method of sub-class
override the method of super-class.
We can achieve Run Time Polymorphism, with the help Method Overriding.
//Circle.java
class Polygon {
public void area() {
System.out.println(“Area of Polygon is calculated”);
} }
class Circle extends Polygon {
public void area() {
System.out.println(“Area of Circle is calculated”);
}
public static void main(String args[]) {
// If a parent type reference refers to child object
Polygon p = new Circle();
// circle’s area() is called. This is called Run Time
Polymorphism.
p.area();
}
}
Output- Area of Circle is calculated
Rules for method overriding
1. Overriding and Access-Modifiers: To understand this, first we know about access-modifiers. So, In short
we discuss here access-modifiers later see in detail.
Access Modifier within class within package outside package
by subclass only
outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
A default/protected/private method (defined in child-class) can’t be overriding the public method (defined in
parent-class) but vice-versa is true.
1-Overriding and access modifiers
// Test.java
class First {
public void show1() {
System.out.println("S. Globe");
}
}
class Second extends First {
void show1() {
System.out.println("Sparsh Globe");
}
}
class Test {
public static void main(String args[]) {
Second t = new Second();
t.show1();
}
}
Output –
error: show1() in Second cannot override show1() in First
void show1() {
^
attempting to assign weaker access privileges; was public
2-Overriding and Final
If we declare a method as final in java, it means that we cannot override this method.
//FinalMethod.java
class First {
final void show1() {
System.out.println("Final Method");
}
}
class Second extends First {
void show1() {
System.out.println("Sparsh Globe");
}
}
class FinalMethod {
public static void main(String args[])
{
Second t = new Second();
t.show1();
}
}
Output –
error: show1() in Second cannot override show1() in First
void show1() {
^
overridden method is final
3-Overriding and static method
In the case static method, it will execute
like overriding but this concept is not
called overriding because of not
achieving Run-Time Polymorphism.
Hence the answer is – we cannot
override the static method. This concept
is known as Method Hiding.
A static method cannot be overridden by
an instance method and an instance
method cannot be hidden by static
method.
class First { //StaticMethod.java
static void show1() {
System.out.println("Final Method");
}
}
class Second extends First {
void show1() {
System.out.println("Sparsh Globe");
}
}
class StaticMethod {
public static void main(String args[]) {
Second t = new Second();
t.show1();
}
}
Output –
Sparsh Globe
4 & 5 - Private
4. Private methods cannot be overridden due to bonded during compile time.
5.We cannot override the method if we change the return type of both the method before JDK 5.0 but in
advanced version of JDK it possible to override with different return type with few conditions:
i. A method must have a return-type of type current class – type.
ii. Method must return current class object.
4 & 5 - Private
Example – (Test.java) – This concept is called covariant return type.
class First {
First show1() {
System.out.println("Final Method");
return new First();
}
}
class Second extends First {
Second show1() {
System.out.println("Sparsh Globe");
return new Second();
}
}
class Test {
public static void
main(String args[]) {
Second t = new Second();
t.show1();
}
}
Output –
Sparsh Globe
Constructor in inheritance
In java, constructor in inheritance operates in different way i.e. un-parameterized constructor of base class gets
automatically called in child-class constructor.
Example – (ConstructorInInheritance.java)
class First {
First() {
System.out.println("Base class");
}
}
class Second extends First {
Second() {
System.out.println("Child class");
}
}
class ConstructorInInheritance {
public static void main(String args[]) {
new Second();
}
}
Output - Base class
Child class
Constructor in inheritance
But if we want to call parameterized constructor defined in base class, then we must use super() method but
remember this method must be the first line in child-class constructor.
Example – (ConstructorInInheritance.java)
class First {
First(int x) {
System.out.println("Base class - "+x);
}
}
class Second extends First {
Second() {
Super(10);
System.out.println("Child class");
}
}
class ConstructorInInheritance {
public static void main(String args[]) {
new Second();
}
} Output - Base class - 10
Child class
Note – Constructors are never being inherited.
Static binding
Static binding is also known as Early Binding. If the type of object is determined by the compiler, then it is
known as Static Binding. If any class has private, final or static method, it means there is static binding.
Example – (StaticBinding.java)
class StaticBinding {
private void show() {
System.out.println("static binding");
}
public static void main(String args[]) {
StaticBinding sb = new StaticBinding ();
sb.show();
}
} Output – static binding
dynamic binding
If the type of object is determined at run-time then it is known as Dynamic Binding. It is also known as Late
Binding.
Example – (DynamicBinding.java)
class Polygon {
void area(){
System.out.println("Area of Polygon");
}
}
class Circle extends Polygon {
void area(){
System.out.println("Area of Circle");
}
}
class Test {
public static void main(String args[]){
Polygon p=new Circle();
p.area();
}
}
Output – Area of Circle
Lecture   6 inheritance

Más contenido relacionado

La actualidad más candente

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
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 examplesSunil Kumar Gunasekaran
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMmanish kumar
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 

La actualidad más candente (20)

Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Java basic
Java basicJava basic
Java basic
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
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
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 

Similar a Lecture 6 inheritance

UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesSakkaravarthiS1
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance SlidesAhsan Raja
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interfaceShubham Sharma
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppthenokmetaferia1
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.pptRassjb
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritanceKalai Selvi
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsBhathiya Nuwan
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالMahmoud Alfarra
 
Chapter 05 polymorphism
Chapter 05 polymorphismChapter 05 polymorphism
Chapter 05 polymorphismNurhanna Aziz
 

Similar a Lecture 6 inheritance (20)

UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Java02
Java02Java02
Java02
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Core java oop
Core java oopCore java oop
Core java oop
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Chap11
Chap11Chap11
Chap11
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class Diagrams
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Chapter 05 polymorphism
Chapter 05 polymorphismChapter 05 polymorphism
Chapter 05 polymorphism
 

Último

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Último (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Lecture 6 inheritance

  • 2. Contents  Introduction to Inheritance  Importance of Inheritance & Sample code  Types of Inheritance  Aggregation in java  Method Overriding  Rules for Method Overriding  Constructor in Inheritance  Static and Dynamic Binding
  • 3. inheritance  Inheritance is a mechanism in java by which one class object is allow to inherit the features i.e. fields & methods of another class object.  The class whose features are inherited is called parent/base/super class and the class that inherits the features is called child/sub/derived class.  Inheritance in java represents the IS-A relationship which is also called parent-child relationship.  We used extends keyword to inherit the features of a class. Following is the syntax of extends keyword: class Child-class extends Parent-class { // methods; } Importance of Inheritance Method Overriding – We can achieved run-time polymorphism Code Reusability – Inheritance support the concept Reusability, i.e. you can reuse the fields & methods of the existing class into new created class.
  • 4. Sample Code class Employee{ float salary=40000; } class Developer extends Employee{ int bonus=10000; public static void main(String args[]){ Developer d=new Developer (); System.out.println("Programmer salary is:"+d.salary); System.out.println("Bonus of Programmer is:"+d.bonus); } } Output - Programmer salary is: 40000.0 Bonus of programmer is: 10000 Employee.java In this code, Developer object can access the field of own class as well as of Employee class, i.e. code reusability. As we seeing in this code, Developer is the child class and Employee is the parent class. The relationship between the classes is Developer IS-A Employee. It means that Developer is a type of Employee.
  • 6. Single inheritance In single inheritance, one sub-class and one-super- class. Super-class Sub-class // Test.java class Demo { void display() { System.out.println(“Sparsh Globe”); } } class Test extends Demo { public static void main(String args[]) { Demo d = new Demo(); d.display(); } } Output - Sparsh Globe In this example, we can see that Test class inherit the features of Demo class, so there is a single inheritance.
  • 7. Multilevel inheritance When there is a chain of inheritance is called Multilevel Inheritance, i.e. when a derived class act as the parent class to other class. //Main.java class First { void show1() { System.out.println(“S. Globe”); } } Class Second extends First { void show2() { System.out.println(“Sparsh Globe”); } } class Third extends Second { void show3() { System.out.println(“Third Class”); } } class Main { public static void main(String args[]) { Third t = new Third(); t.show1(); t.show2(); t.show3(); } } Output - S. Globe Sparsh Globe Third Class A B C
  • 8. Hierarchal inheritance A single class can inherited by two or more than two class, known as Hierarchal Inheritance. A AAA // Test.java class First { void show1() { System.out.println("S. Globe"); } } class Second extends First { void show2() { System.out.println("Sparsh Globe"); } } class Third extends First { void show3() { System.out.println("Third Class"); } } class Test { public static void main(String args[]) { Third t = new Third(); t.show1(); t.show3(); Second s = new Second(); s.show2(); } } Output - S. Globe Third Class Sparsh Globe
  • 9. Multiple inheritance In this, there are two or more than two parent class exist. That is, one subclass can have two or more than two parent class. Multiple Inheritance does not supported in java. A C B In Java, we can achieve multiple inheritance only through interfaces. To reduce the complexity, multiple inheritance does not support in java.
  • 10. Multiple & hybrid inheritance Multiple inheritance is not supported in java. Let’s understand this with a scenario as discussed below: For Example - 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 the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Hybrid Inheritance - It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.
  • 11. aggregation Aggregation represents HAS-A relationship and if a class have an entity reference, it is known as Aggregation. Let’s consider an example; suppose a Circle object contains one more object named Operation, which contains its operation like square, area, etc. Example – class Circle { double pi = 3.14; Operation op; // Operation is a class } In such case Circle has an entity reference op, so relationship is Circle HAS-A op.
  • 12. Aggregation (contd..) Aggregation is used for Code Reusability. Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice. Example - //Address.java public class Address { String city,state,country; public Address(String city, String state, String country) { this.city = city; this.state = state; this.country = country; } }
  • 13. aggregation //Emp.java public class Emp { int id; String name; Address address; public Emp(int id, String name,Address address) { this.id = id; this.name = name; this.address=address; } void display(){ System.out.println(id+" "+name); System.out.println(address.city+" "+address.state+" " +address.country); } public static void main(String[] args) { Address address1=new Address("KNP","UP","india"); Address address2=new Address("LKO","UP","india"); Emp e=new Emp(101,"Manish",address1); Emp e2=new Emp(102,"Sparsh",address2); e.display(); e2.display(); } } Output – 101 Manish KNP UP India 102 Sparsh LKO UP India
  • 14. Method overriding Overriding is a concept in which a sub-class to provide a specific implementation of a method that is already provided by one of its super-class. In this concept, sub-class has a method with same name, parameter/signature and return type as contains in super-class. In this case we say that method of sub-class override the method of super-class. We can achieve Run Time Polymorphism, with the help Method Overriding. //Circle.java class Polygon { public void area() { System.out.println(“Area of Polygon is calculated”); } } class Circle extends Polygon { public void area() { System.out.println(“Area of Circle is calculated”); } public static void main(String args[]) { // If a parent type reference refers to child object Polygon p = new Circle(); // circle’s area() is called. This is called Run Time Polymorphism. p.area(); } } Output- Area of Circle is calculated
  • 15. Rules for method overriding 1. Overriding and Access-Modifiers: To understand this, first we know about access-modifiers. So, In short we discuss here access-modifiers later see in detail. Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y A default/protected/private method (defined in child-class) can’t be overriding the public method (defined in parent-class) but vice-versa is true.
  • 16. 1-Overriding and access modifiers // Test.java class First { public void show1() { System.out.println("S. Globe"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class Test { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – error: show1() in Second cannot override show1() in First void show1() { ^ attempting to assign weaker access privileges; was public
  • 17. 2-Overriding and Final If we declare a method as final in java, it means that we cannot override this method. //FinalMethod.java class First { final void show1() { System.out.println("Final Method"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class FinalMethod { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – error: show1() in Second cannot override show1() in First void show1() { ^ overridden method is final
  • 18. 3-Overriding and static method In the case static method, it will execute like overriding but this concept is not called overriding because of not achieving Run-Time Polymorphism. Hence the answer is – we cannot override the static method. This concept is known as Method Hiding. A static method cannot be overridden by an instance method and an instance method cannot be hidden by static method. class First { //StaticMethod.java static void show1() { System.out.println("Final Method"); } } class Second extends First { void show1() { System.out.println("Sparsh Globe"); } } class StaticMethod { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – Sparsh Globe
  • 19. 4 & 5 - Private 4. Private methods cannot be overridden due to bonded during compile time. 5.We cannot override the method if we change the return type of both the method before JDK 5.0 but in advanced version of JDK it possible to override with different return type with few conditions: i. A method must have a return-type of type current class – type. ii. Method must return current class object.
  • 20. 4 & 5 - Private Example – (Test.java) – This concept is called covariant return type. class First { First show1() { System.out.println("Final Method"); return new First(); } } class Second extends First { Second show1() { System.out.println("Sparsh Globe"); return new Second(); } } class Test { public static void main(String args[]) { Second t = new Second(); t.show1(); } } Output – Sparsh Globe
  • 21. Constructor in inheritance In java, constructor in inheritance operates in different way i.e. un-parameterized constructor of base class gets automatically called in child-class constructor. Example – (ConstructorInInheritance.java) class First { First() { System.out.println("Base class"); } } class Second extends First { Second() { System.out.println("Child class"); } } class ConstructorInInheritance { public static void main(String args[]) { new Second(); } } Output - Base class Child class
  • 22. Constructor in inheritance But if we want to call parameterized constructor defined in base class, then we must use super() method but remember this method must be the first line in child-class constructor. Example – (ConstructorInInheritance.java) class First { First(int x) { System.out.println("Base class - "+x); } } class Second extends First { Second() { Super(10); System.out.println("Child class"); } } class ConstructorInInheritance { public static void main(String args[]) { new Second(); } } Output - Base class - 10 Child class Note – Constructors are never being inherited.
  • 23. Static binding Static binding is also known as Early Binding. If the type of object is determined by the compiler, then it is known as Static Binding. If any class has private, final or static method, it means there is static binding. Example – (StaticBinding.java) class StaticBinding { private void show() { System.out.println("static binding"); } public static void main(String args[]) { StaticBinding sb = new StaticBinding (); sb.show(); } } Output – static binding
  • 24. dynamic binding If the type of object is determined at run-time then it is known as Dynamic Binding. It is also known as Late Binding. Example – (DynamicBinding.java) class Polygon { void area(){ System.out.println("Area of Polygon"); } } class Circle extends Polygon { void area(){ System.out.println("Area of Circle"); } } class Test { public static void main(String args[]){ Polygon p=new Circle(); p.area(); } } Output – Area of Circle