SlideShare uma empresa Scribd logo
1 de 40
INHERITANCE
Dr.K.Kalaiselvi
Dept of Computer Science
Kristu Jayanti College
Bangalore
• Inheritance is the mechanism in java by which one class acquires the
features(fields and methods) of another class.
Important terminology:
• Super Class: The class whose features are inherited is known as super
class(or a base class or a parent class).
• Sub Class: The class that inherits the other class is known as sub class(or a
derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some
of the code that we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods of the existing
class.
• The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
class Employee{
float salary=4000;
}
class Programmer extends Employee{
int bonus=1000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary); //parent
class variable System.out.println("Bonus of Programmer
is:"+p.bonus); /child class variable
}
}
class Calculation
{
int z;
public void addition(int x, int y)
{ z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{ z = x - y;
System.out.println("The difference between the given
numbers:"+z);
} }
public class My_Calculation extends Calculation
{
public void multiplication(int x, int y)
{ z = x * y;
System.out.println("The product of the given
numbers:"+z); } public static void main(String
args[])
{
int a = 20, b = 10;
My_Calculation demo = new
My_Calculation(); demo.addition(a, b);
• Child class objects has variables/methods of parent class as
well as itself.
TYPES OF INHERITANCE IN
JAVA
• On the basis of class, there can be three types of inheritance in java:
single, multilevel
and hierarchical.
• In java programming, multiple and hybrid inheritance is supported
through interface only. Multiple inheritance is not supported using
classes in java.
SINGLE
INHERITANCE
• In single inheritance, subclasses inherit the features of one superclass.
In image below,
the class A serves as a base class for the derived class B.
class Animal{
void eats(){System.out.println(“All animals
eat...");}
}
class Dog extends Animal{
void barks(){System.out.println(“only dogs
barks...");}
}
class TestInheritance{
public static void main(String
args[]){ Dog d=new Dog();
d.barks();
d.eats();
}
}
class one
{
public void print_one()
{
System.out.println(“Kristu
");
}
}
class two extends one
{
public void print_ftwo()
{
System.out.println(“Jay
anti");
}
}
public class Main
{
public static void main(String[]
args)
{
two g = new
two();
g.print_one();
g.print_two();
}
}
MULTILEVEL
INHERITANCE
• In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class.
• In below image, the class A serves as a base class for the derived class
B, which in turn
serves as a base class for the derived class C.
class
Animal{
void eat()
{System.out.println(“All animals
eat...");}
}
class Dog extends Animal{
Void bark()
{System.out.println(“Only dogs
barkis");}
}
class BabyDog extends Dog{
void weep()
{System.out.println(“Baby dogs
weep");}
}
class TestInheritance2{
public static void main(String
args[]){ BabyDog d=new
BabyDog(); d.weep();
d.bark();
d.eat();
}
}
class one
{
public void print_one()
{
System.out.println(“Kristu
"); }
}
class two extends one
{
public void print_two()
{
System.out.println(“Jayan
ti"); }
}
class three extends two
{
public void print_three()
{
System.out.println(“College"
); }
public class Main
{
public static void main(String[]
args)
{
three g = new
three();
g.print_one();
g.print_two();
g.print_three();
}
}
HIERARCHICAL
INHERITANCE
• In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than
one sub class.
• In below image, the class A serves as a base class for the derived class
B,C and D.
class one
{
public void print_one)
{
System.out.println(“Kri
stu");
}
}
class two extends one
{
public void print_two()
{
System.out.println(“Jaya
nti");
}
}
class three extends
one
{
/*............*/
}
public class
Main
{
public static void main(String[]
args)
{
three g = new
three();
g.print_one();
two t = new
two();
t.print_two();
g.print_one();
}
}
class A {
public void methodA() {
System.out.println("method of
Class A");
}
}
class B extends A {
public void
methodB() {
System.out.println("method of
Class B");
}
}
class C extends A {
public void methodC() {
System.out.println("method of
Class C");
}
}
class D extends A {
class JavaExample
{
public static void main(String
args[])
{
B obj1 = new
B(); C obj2 =
new C(); D
obj3 = new
D();
//All classes can access the
method of
class A
obj1.method
A();
obj2.method
A();
obj3.method
METHOD
OVERRIDING
• Declaring a method in sub class which is already present in parent
class is known as
method overriding, provided that it is not marked final..
• Overriding is done so that a child class can give its own
implementation to a method which is already provided by the parent
class.
• In this case the method in parent class is called overridden method
and the method in child class is called overriding method.
• The version of a method that is executed will be determined by the
object that is used to invoke it. If an object of a parent class is used to
invoke the method, then the version in the parent class will be executed,
but if an object of the subclass is used to invoke the method, then the
version in the child class will be executed.
• In other words, it is the type of the object being referred to (not the type
of the reference
variable) that determines which version of an overridden method will be
executed.
class Animal {
public void move() {
System.out.println("Animals can
move");
}
}
class Dog extends
Animal { public void
move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal robject
Animal b = new Dog(); // Animal
reference but Dog object
a.move();// runs the method in Animal
class b.move(); // runs the
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.
• Constructors cannot be overridden.
• The access level cannot be more restrictive than the overridden
method's access level. For example: If the superclass method is
declared public then the overridding method in the sub class cannot be
either private or protected.
• The argument list should be exactly the same as that of the overridden
method.
• The return type should be the same or a subtype of the return type
declared in the original overridden method in the superclass.
class Parent {
// private methods are not
overridden private void m1()
{
System.out.println("From parent
m1()"); } protected void m2()
{
System.out.println("From parent
m2()"); }
}
class Child extends Parent {
// new m1() method ,unique to
Child class private void m1()
{
System.out.println("From child
m1()");
}
// overriding method with more
accessibility public void m2()
{
System.out.println("From child
m2()");
}
//
Driv
er
class
class
Mai
n {
public static void main(String[]
args)
{
Parent obj1 = new
Parent(); obj1.m2();
Child obj2 = new Child();
Parent obj3=new
Child();//Upcasting
obj2.m2(); //overriding
obj3.m2();
}
}
• When Parent class reference variable refers to Child class
object, it is known as Upcasting.
• In Java this is helpful in scenarios where multiple child classes extends
one parent class.
In those cases we can create a parent class reference and assign child
class objects to it.
DYNAMIC METHOD DISPATCH OR RUNTIME
POLYMORPHISM
• Method overriding is one of the ways in which Java supports Runtime
Polymorphism. Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time, rather than
compile time.
• When an overridden method is called through a superclass reference,
Java determines which version(superclass/subclasses) of that method is
to be executed based upon the type of the object being referred to at the
time the call occurs. Thus, this determination is made at run time.
• At run-time, it depends on the type of the object being referred to (not
the type of the reference variable) that determines which version of
an overridden method will be executed
• A superclass reference variable can refer to a subclass object. This is
also known as upcasting. Java uses this fact to resolve calls to
overridden methods at run time.
•
class Game
{
public void type()
{
System.out.println("Indoor &
outdoor");
}
}
Class Cricket extends Game
{
public void type()
{
System.out.println("outdoor
game");
}
}
Class dynamicdispatch{
public static void main(String[] args)
{
Game gm = new
Game(); Cricket ck =
new Cricket();
gm.type();
ck.type();
gm = ck;//gm refers to Cricket
object,dynamic method dispatch
gm.type(); //calls Cricket's version of
type
}
}
class Shape{
void
draw(){System.out.println("drawing..");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing
rectangle..");
}
}
class Circle extends Shape{
void draw(){System.out.println("drawing
circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing
triangle...");}
}
class
TestPolymorphism2{
public static void main(String
args[])
{
Shape s;
s=new
Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new
Triangle();
s.draw();
}
}
OVERLOADI
NG
• Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.
• 1. Number of parameters.
For example: This is a valid case of overloading
add(int, int) add(int, int, int)
• 2. Data type of parameters.
For example:add(int, int) add(int, float)
• 3. Sequence of Data type of
parameters. For example:add(int,
float) add(float,
int)
• Invalid case of method overloading:if two methods have same name,
same parameters and have different return type, then this is not a valid
method overloading example. This will throw compilation error.
int add(int, int) float add(int, int)
• Method overloading is an example of Static Polymorphism.
• Points to Note:
1.Static Polymorphism is also known as compile time binding or early
binding.
2.Static binding happens at compile time. Method overloading is an
example of static binding where binding of method call to its definition
happens at Compile time.
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num) //different number of
parameters
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new
DisplayOverloading(); obj.disp('a');
obj.disp('a',10);
}
}
class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)different type of paarameter
{
System.out.println(c );
}
}
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new
DisplayOverloading2(); obj.disp('a');
obj.disp(5);
}
}
class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method
disp");
}
public void disp(int num, char c)//different sequence of
parameters
{
System.out.println("I’m the second definition of
method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new
DisplayOverloading3(); obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
ABSTRACT CLASS AND ABSTRACT
METHOD
• A class which is declared as abstract is known as an abstract class. It can
have abstract and non-abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change
the body of the method.
• A method which is declared as abstract and does not have implementation
is known as an abstract method.
• If a class includes abstract methods, then the class itself must be declared
abstract
abstract class Shape{
abstract void draw();
public void
nonabstract(){
System.out.println(“Non abstrat method");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing
rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing
circle");}
}
class AbstractionTest1{
public static void main(String
args[]){ Shape s=new
Circle1();
s.draw();
s.nonabstractmethod();
SUPER
KEYWORD
• The super keyword in Java is a reference variable which is used to
refer immediate
parent class object.
• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
Use of super with
variables class
Vehicle
{
int maxSpeed =
120;
}
/* sub class Car extending
vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base
class (vehicle) */
System.out.println("Maximum
Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void
main(String[] args)
{
Car small = new Car();
small.display();
}
}
• Use of super with methods
class Person
{
void message()
{
System.out.println("This is person
class");
}
}
class Student extends Person
{
void message()
{
System.out.println("This is student
class");
}
void display()
{ // will invoke or call current class
message() method
message();
// will invoke or call parent class
message()
method
super.message();
}
class Test
{
public static void main(String
args[])
{
Student s = new Student();
// calling display() of
Student
s.display();
}
}
Use of super with constructors
class Person
{
Person()
{
System.out.println("Person
class Constructor");
}
}
class Student extends Person
{
Student()
{
// invoke or call parent class
constructor super();
System.out.println("Student
class Constructor");
}
}
class Test
{
public static void
main(String[] args)
{
Student s = new Student();
}
}
• Call to super() must be first statement in Derived(Student)
Class
constructor.
• If a constructor does not explicitly invoke a superclass
constructor, the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.
• If the superclass does not have a no-argument
constructor, you will
get a compile-time error.
• If a subclass constructor invokes a constructor of its
superclass, either explicitly or implicitly, a whole chain of
constructors called, all the way back to the constructor of
Object. This, in fact, is the case. It is
called constructor chaining..
THIS
KEYWORD
• ‘this’ is a reference variable that refers to the current object.
• The most common use of the this keyword is to eliminate the confusion
between class
attributes and parameters with the same name
• Invoke current class constructor
• Invoke current class method
class
Test
{
int a;
int b;
// Parameterized
constructor Test(int a,
int b)
{
this.a = a;
this.b = b;
}
void display()
{
//Displaying value of variables a
and b System.out.println("a = " + a
+ " b = " + b);
}
}
class ThisEx1{
public static void
main(String[] args)
{
Test object = new
Test(10, 20);
object.display();
}
}
class Test
{
int
a;
int
b;
//Default
constructor
Test()
{
this(10, 20);
System.out.println("Inside default
constructor n");
}
//Parameterized
constructor Test(int a,
int b)
{
this.a =
a;
Class thisEx2{ public static void
main(String[] args)
{
Test object = new Test();
}
}
Unit3 inheritance

Mais conteúdo relacionado

Mais procurados

Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
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
Sunil Kumar Gunasekaran
 

Mais procurados (20)

Introduction to java
Introduction to  javaIntroduction to  java
Introduction to java
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objects
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes 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
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Pi j4.1 packages
Pi j4.1 packagesPi j4.1 packages
Pi j4.1 packages
 

Semelhante a Unit3 inheritance

Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
sotlsoc
 

Semelhante a Unit3 inheritance (20)

Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java
JavaJava
Java
 
Core java oop
Core java oopCore java oop
Core java oop
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
 
Oops
OopsOops
Oops
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 

Mais de Kalai Selvi

Mais de Kalai Selvi (19)

cloud services and providers
cloud services and providerscloud services and providers
cloud services and providers
 
cloud concepts and technologies
cloud concepts and technologiescloud concepts and technologies
cloud concepts and technologies
 
cloud computing
cloud computingcloud computing
cloud computing
 
I Semester-Unit 3 Boolean Algebra.pptx
I Semester-Unit 3 Boolean Algebra.pptxI Semester-Unit 3 Boolean Algebra.pptx
I Semester-Unit 3 Boolean Algebra.pptx
 
I semester-SOP-POS expressions.pptx
I semester-SOP-POS expressions.pptxI semester-SOP-POS expressions.pptx
I semester-SOP-POS expressions.pptx
 
I Semester-Unit 3 Boolean Algebra.pptx
I Semester-Unit 3 Boolean Algebra.pptxI Semester-Unit 3 Boolean Algebra.pptx
I Semester-Unit 3 Boolean Algebra.pptx
 
Multimedia Authoring Tools.ppt
Multimedia Authoring Tools.pptMultimedia Authoring Tools.ppt
Multimedia Authoring Tools.ppt
 
Process of Making Multimedia.ppt
Process of Making Multimedia.pptProcess of Making Multimedia.ppt
Process of Making Multimedia.ppt
 
Introduction to Artificial Intelligence
Introduction to Artificial IntelligenceIntroduction to Artificial Intelligence
Introduction to Artificial Intelligence
 
Searching techniques in AI
Searching techniques in AISearching techniques in AI
Searching techniques in AI
 
Introduction to Artificial Intelligence
Introduction to Artificial IntelligenceIntroduction to Artificial Intelligence
Introduction to Artificial Intelligence
 
AWT controls, Listeners
AWT controls, ListenersAWT controls, Listeners
AWT controls, Listeners
 
AWT controls, Listeners
AWT controls, ListenersAWT controls, Listeners
AWT controls, Listeners
 
Unit 1 part 2
Unit 1  part 2Unit 1  part 2
Unit 1 part 2
 
Unit 1 part 1
Unit 1   part 1Unit 1   part 1
Unit 1 part 1
 
Unit 4 combinational circuit
Unit 4 combinational circuitUnit 4 combinational circuit
Unit 4 combinational circuit
 
Unit 3 file management
Unit 3 file managementUnit 3 file management
Unit 3 file management
 
Unit 3 chapter 1-file management
Unit 3 chapter 1-file managementUnit 3 chapter 1-file management
Unit 3 chapter 1-file management
 
Unit 2chapter 2 memory mgmt complete
Unit 2chapter 2  memory mgmt completeUnit 2chapter 2  memory mgmt complete
Unit 2chapter 2 memory mgmt complete
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
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
QucHHunhnh
 

Último (20)

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.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
 
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"
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
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
 

Unit3 inheritance

  • 1. INHERITANCE Dr.K.Kalaiselvi Dept of Computer Science Kristu Jayanti College Bangalore
  • 2. • Inheritance is the mechanism in java by which one class acquires the features(fields and methods) of another class. Important terminology: • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class). • Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods. • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class. • The keyword used for inheritance is extends. Syntax : class derived-class extends base-class { //methods and fields }
  • 3. class Employee{ float salary=4000; } class Programmer extends Employee{ int bonus=1000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); //parent class variable System.out.println("Bonus of Programmer is:"+p.bonus); /child class variable } }
  • 4. class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:"+z); } public void Subtraction(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:"+z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers:"+z); } public static void main(String args[]) { int a = 20, b = 10; My_Calculation demo = new My_Calculation(); demo.addition(a, b);
  • 5. • Child class objects has variables/methods of parent class as well as itself.
  • 6. TYPES OF INHERITANCE IN JAVA • On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. • In java programming, multiple and hybrid inheritance is supported through interface only. Multiple inheritance is not supported using classes in java.
  • 7.
  • 8. SINGLE INHERITANCE • In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.
  • 9. class Animal{ void eats(){System.out.println(“All animals eat...");} } class Dog extends Animal{ void barks(){System.out.println(“only dogs barks...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.barks(); d.eats(); } }
  • 10. class one { public void print_one() { System.out.println(“Kristu "); } } class two extends one { public void print_ftwo() { System.out.println(“Jay anti"); } } public class Main { public static void main(String[] args) { two g = new two(); g.print_one(); g.print_two(); } }
  • 11. MULTILEVEL INHERITANCE • In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. • In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C.
  • 12. class Animal{ void eat() {System.out.println(“All animals eat...");} } class Dog extends Animal{ Void bark() {System.out.println(“Only dogs barkis");} } class BabyDog extends Dog{ void weep() {System.out.println(“Baby dogs weep");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); } }
  • 13. class one { public void print_one() { System.out.println(“Kristu "); } } class two extends one { public void print_two() { System.out.println(“Jayan ti"); } } class three extends two { public void print_three() { System.out.println(“College" ); } public class Main { public static void main(String[] args) { three g = new three(); g.print_one(); g.print_two(); g.print_three(); } }
  • 14. HIERARCHICAL INHERITANCE • In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class. • In below image, the class A serves as a base class for the derived class B,C and D.
  • 15. class one { public void print_one) { System.out.println(“Kri stu"); } } class two extends one { public void print_two() { System.out.println(“Jaya nti"); } } class three extends one { /*............*/ } public class Main { public static void main(String[] args) { three g = new three(); g.print_one(); two t = new two(); t.print_two(); g.print_one(); } }
  • 16. class A { public void methodA() { System.out.println("method of Class A"); } } class B extends A { public void methodB() { System.out.println("method of Class B"); } } class C extends A { public void methodC() { System.out.println("method of Class C"); } } class D extends A { class JavaExample { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); //All classes can access the method of class A obj1.method A(); obj2.method A(); obj3.method
  • 17. METHOD OVERRIDING • Declaring a method in sub class which is already present in parent class is known as method overriding, provided that it is not marked final.. • Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. • In this case the method in parent class is called overridden method and the method in child class is called overriding method. • The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. • In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
  • 18. class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal robject Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move(); // runs the
  • 19. • A method declared final cannot be overridden. • A method declared static cannot be overridden but can be re-declared. • If a method cannot be inherited, then it cannot be overridden. • Constructors cannot be overridden. • The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. • The argument list should be exactly the same as that of the overridden method. • The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
  • 20. class Parent { // private methods are not overridden private void m1() { System.out.println("From parent m1()"); } protected void m2() { System.out.println("From parent m2()"); } } class Child extends Parent { // new m1() method ,unique to Child class private void m1() { System.out.println("From child m1()"); } // overriding method with more accessibility public void m2() { System.out.println("From child m2()"); } // Driv er class class Mai n { public static void main(String[] args) { Parent obj1 = new Parent(); obj1.m2(); Child obj2 = new Child(); Parent obj3=new Child();//Upcasting obj2.m2(); //overriding obj3.m2(); } }
  • 21. • When Parent class reference variable refers to Child class object, it is known as Upcasting. • In Java this is helpful in scenarios where multiple child classes extends one parent class. In those cases we can create a parent class reference and assign child class objects to it.
  • 22. DYNAMIC METHOD DISPATCH OR RUNTIME POLYMORPHISM • Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. • When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. • At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed • A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses this fact to resolve calls to overridden methods at run time. •
  • 23. class Game { public void type() { System.out.println("Indoor & outdoor"); } } Class Cricket extends Game { public void type() { System.out.println("outdoor game"); } } Class dynamicdispatch{ public static void main(String[] args) { Game gm = new Game(); Cricket ck = new Cricket(); gm.type(); ck.type(); gm = ck;//gm refers to Cricket object,dynamic method dispatch gm.type(); //calls Cricket's version of type } }
  • 24. class Shape{ void draw(){System.out.println("drawing..");} } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle.."); } } class Circle extends Shape{ void draw(){System.out.println("drawing circle...");} } class Triangle extends Shape{ void draw(){System.out.println("drawing triangle...");} } class TestPolymorphism2{ public static void main(String args[]) { Shape s; s=new Rectangle(); s.draw(); s=new Circle(); s.draw(); s=new Triangle(); s.draw(); } }
  • 25. OVERLOADI NG • Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. • 1. Number of parameters. For example: This is a valid case of overloading add(int, int) add(int, int, int) • 2. Data type of parameters. For example:add(int, int) add(int, float) • 3. Sequence of Data type of parameters. For example:add(int, float) add(float, int) • Invalid case of method overloading:if two methods have same name, same parameters and have different return type, then this is not a valid method overloading example. This will throw compilation error. int add(int, int) float add(int, int)
  • 26. • Method overloading is an example of Static Polymorphism. • Points to Note: 1.Static Polymorphism is also known as compile time binding or early binding. 2.Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
  • 27. class DisplayOverloading { public void disp(char c) { System.out.println(c); } public void disp(char c, int num) //different number of parameters { System.out.println(c + " "+num); } } class Sample { public static void main(String args[]) { DisplayOverloading obj = new DisplayOverloading(); obj.disp('a'); obj.disp('a',10); } }
  • 28. class DisplayOverloading2 { public void disp(char c) { System.out.println(c); } public void disp(int c)different type of paarameter { System.out.println(c ); } } class Sample2 { public static void main(String args[]) { DisplayOverloading2 obj = new DisplayOverloading2(); obj.disp('a'); obj.disp(5); } }
  • 29. class DisplayOverloading3 { public void disp(char c, int num) { System.out.println("I’m the first definition of method disp"); } public void disp(int num, char c)//different sequence of parameters { System.out.println("I’m the second definition of method disp" ); } } class Sample3 { public static void main(String args[]) { DisplayOverloading3 obj = new DisplayOverloading3(); obj.disp('x', 51 ); obj.disp(52, 'y'); } }
  • 30. ABSTRACT CLASS AND ABSTRACT METHOD • A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. • An abstract class must be declared with an abstract keyword. • It can have abstract and non-abstract methods. • It cannot be instantiated. • It can have constructors and static methods also. • It can have final methods which will force the subclass not to change the body of the method. • A method which is declared as abstract and does not have implementation is known as an abstract method. • If a class includes abstract methods, then the class itself must be declared abstract
  • 31. abstract class Shape{ abstract void draw(); public void nonabstract(){ System.out.println(“Non abstrat method");} } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle1 extends Shape{ void draw(){System.out.println("drawing circle");} } class AbstractionTest1{ public static void main(String args[]){ Shape s=new Circle1(); s.draw(); s.nonabstractmethod();
  • 32. SUPER KEYWORD • The super keyword in Java is a reference variable which is used to refer immediate parent class object. • super can be used to refer immediate parent class instance variable. • super can be used to invoke immediate parent class method. • super() can be used to invoke immediate parent class constructor.
  • 33. Use of super with variables class Vehicle { int maxSpeed = 120; } /* sub class Car extending vehicle */ class Car extends Vehicle { int maxSpeed = 180; void display() { /* print maxSpeed of base class (vehicle) */ System.out.println("Maximum Speed: " + super.maxSpeed); } } /* Driver program to test */ class Test { public static void main(String[] args) { Car small = new Car(); small.display(); } }
  • 34. • Use of super with methods class Person { void message() { System.out.println("This is person class"); } } class Student extends Person { void message() { System.out.println("This is student class"); } void display() { // will invoke or call current class message() method message(); // will invoke or call parent class message() method super.message(); } class Test { public static void main(String args[]) { Student s = new Student(); // calling display() of Student s.display(); } }
  • 35. Use of super with constructors class Person { Person() { System.out.println("Person class Constructor"); } } class Student extends Person { Student() { // invoke or call parent class constructor super(); System.out.println("Student class Constructor"); } } class Test { public static void main(String[] args) { Student s = new Student(); } }
  • 36. • Call to super() must be first statement in Derived(Student) Class constructor. • If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. • If the superclass does not have a no-argument constructor, you will get a compile-time error. • If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, a whole chain of constructors called, all the way back to the constructor of Object. This, in fact, is the case. It is called constructor chaining..
  • 37. THIS KEYWORD • ‘this’ is a reference variable that refers to the current object. • The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name • Invoke current class constructor • Invoke current class method
  • 38. class Test { int a; int b; // Parameterized constructor Test(int a, int b) { this.a = a; this.b = b; } void display() { //Displaying value of variables a and b System.out.println("a = " + a + " b = " + b); } } class ThisEx1{ public static void main(String[] args) { Test object = new Test(10, 20); object.display(); } }
  • 39. class Test { int a; int b; //Default constructor Test() { this(10, 20); System.out.println("Inside default constructor n"); } //Parameterized constructor Test(int a, int b) { this.a = a; Class thisEx2{ public static void main(String[] args) { Test object = new Test(); } }