SlideShare una empresa de Scribd logo
1 de 39
INHERITANCE
• 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);
demo.Subtraction(a, b);
demo.multiplication(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(“Jayanti");
}
}
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(“Jayanti"); }
}
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(“Kristu");
}
}
class two extends one
{
public void print_two()
{
System.out.println(“Jayanti");
}
}
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 {
public void methodD() {
System.out.println("method of Class D");
}
}
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.methodA();
obj2.methodA();
obj3.methodA();
}
}
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 method in Dog class
}
}
• 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()");
}
}
// Driver class
class Main {
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();
}
}
OVERLOADING
• 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;
this.b = b;
System.out.println("Inside parameterized
constructor");
}
}
Class thisEx2{
public static void main(String[] args)
{
Test object = new Test();
}
}

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (20)

Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes 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
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
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
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
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
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Introduction to java
Introduction to  javaIntroduction to  java
Introduction to 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
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 

Similar a Unit3 part2-inheritance

Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 

Similar a Unit3 part2-inheritance (20)

UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
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
 
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
JavaJava
Java
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 

Más de DevaKumari Vijay

Más de DevaKumari Vijay (17)

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
 
Os ch1
Os ch1Os ch1
Os ch1
 
Unit2
Unit2Unit2
Unit2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
 
Decisiontree&game theory
Decisiontree&game theoryDecisiontree&game theory
Decisiontree&game theory
 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
 
Operations research lpp
Operations research lppOperations research lpp
Operations research lpp
 

Ú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
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Último (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
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
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.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 ...
 
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
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
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
 

Unit3 part2-inheritance

  • 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); demo.Subtraction(a, b); demo.multiplication(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(“Jayanti"); } } 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(“Jayanti"); } } 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(“Kristu"); } } class two extends one { public void print_two() { System.out.println(“Jayanti"); } } 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 { public void methodD() { System.out.println("method of Class D"); } } 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.methodA(); obj2.methodA(); obj3.methodA(); } }
  • 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 method in Dog class } }
  • 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()"); } } // Driver class class Main { 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. OVERLOADING • 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; this.b = b; System.out.println("Inside parameterized constructor"); } } Class thisEx2{ public static void main(String[] args) { Test object = new Test(); } }