SlideShare a Scribd company logo
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

More Related Content

What's hot

Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
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 polymorphism
mcollison
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
Christopher Akinlade
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam 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 java
CPD INDIA
 
Class or Object
Class or ObjectClass or Object
Class or Object
Rahul Bathri
 
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
manish kumar
 
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
Danairat Thanabodithammachari
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 

What's hot (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 to 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 Interfaces
SakkaravarthiS1
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
Ahsan Raja
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
Shubham Sharma
 
Core java oop
Core java oopCore java oop
Core java oop
Parth Shah
 
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).ppt
henokmetaferia1
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
Rassjb
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem4
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
OOP Concepets and UML Class Diagrams
OOP Concepets and UML Class DiagramsOOP Concepets and UML Class Diagrams
OOP Concepets and UML Class Diagrams
Bhathiya Nuwan
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
wahidullah mudaser
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
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 to 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
 

Recently uploaded

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 

Recently uploaded (20)

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 

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