SlideShare a Scribd company logo
1 of 51
Chapter 7



Inheritance



              http://www.java2all.com
Inheritance



              http://www.java2all.com
What is a Inheritance ?

• The derivation of one class from another class is
  called Inheritance.

• Type of inheritance :




                                             http://www.java2all.com
A
       A


                                             B
       B

Single Inheritance
                      A                       C

                                      Multi level Inheritance

           B          C          D

           Hierarchical Inheritance
                                                  http://www.java2all.com
• A class that is inherited is called a superclass.
• The class that does the inheriting is called as
  subclass.
• In above figure all class A is superclass.
• A subclass inherits all instance variables and
  methods from its superclass and also has its own
  variables and methods.
• One can inherit the class using keyword extends.
  Syntax :
• Class subclass-name extends superclass-name
• {       // body of class.
• }
                                               http://www.java2all.com
In java, a class has only one super class.

     Java does not support Multiple
Inheritance.

     One can create a hierarchy of inheritance
in which a subclass becomes a superclass of
another subclass.

       However, no class can be a superclass of
itself.

                                           http://www.java2all.com
class A //superclass
{
   int num1; //member of superclass
   int num2; //member of superclass
   void setVal(int no1, int no2) //method of superclass
   {
      num1 = no1;
      num2 = no2;
   }
}

class B extends A //subclass B
{
   int multi; //member of subclass
   void mul() //method of subclass
   {
      multi = num1*num2; //accessing member of superclass from subclass
   }
}
                                                                         Output :
class inhe2
{
   public static void main(String args[])
   {
                                                                         Multiplication is 30
     B subob = new B();
     subob.setVal(5,6); //calling superclass method throgh subclass object
     subob.mul();
     System.out.println("Multiplication is " + subob.multi);
   }
}

                                                                                      http://www.java2all.com
Note :          Private members of super
class is not accessible in sub class, super
class is also called parent class or base
class, sub class is also called child class or
derived class.




                                       http://www.java2all.com
Super & Final



                http://www.java2all.com
Super
super :
      super keyword is used to call a superclass
constructor and to call or access super class
members(instance variables or methods).

syntax of super :            super(arg-list)

      When a subclass calls super() it is calling the
constructor of its immediate superclass.

      super() must always be the first statement
executed inside a subclass constructor.
      super.member
Here member can be either method or an instance
variables.                                       http://www.java2all.com
This second form of super is most applicable to
situation in which member names of a subclass hide
member of superclass due to same name.




                                            http://www.java2all.com
class A1
{
   public int i;
   A1()
   {
      i=5;
   }
}
class B1 extends A1
{
   int i;
   B1(int a,int b)
   {
      super(); //calling super class constructor
      //now we will change value of superclass variable i
      super.i=a; //accessing superclass member from subclass
      i=b;
   }
   void show()
   {
      System.out.println("i in superclass = " + super.i );
      System.out.println("i in subclass = " + i );
   }
}
public class Usesuper
                                                        Output :
{
      public static void main(String[] args)
      {
          B1 b = new B1(10,12);
                                                        i in superclass = 10
          b.show();                                     i in subclass = 12
}    }                                                                         http://www.java2all.com
The instance variable i in B1 hides the i in A, super
allows access to the i defined in the superclass.

super can also be used to call methods that are hidden by
a subclass.




                                                    http://www.java2all.com
Final



        http://www.java2all.com
final keyword can be use with variables,
methods and class.
=> final variables.

      When we want to declare constant variable in
java we use final keyword.
      Syntax : final variable name = value;

=> final method
      Syntax : final methodname(arg)

      When we put final keyword before method than
it becomes final method.
                                            http://www.java2all.com
To prevent overriding of method final keyword
is used, means final method cant be override.
=> final class
             A class that can not be sub classed is called
a final class.
      A class that can not be sub classed is called a
final class.
      This is archived in java using the keyword final
as follow.

       Syntax : final class class_name { ... }

      Any attempt to inherit this class will cause an
error and compiler will not allow it.          http://www.java2all.com
final class aa
{
   final int a=10;
   public final void ainc()
   {
      a++; // The final field aa.a cannot be assigned
   }

}

class bb extends aa // The type bb cannot subclass the final class aa
{
   public void ainc() //Cannot override the final method from aa
   {
     System.out.println("a = " + a);

}
   }                                                  Here no output will be
                                               there because all the
public class Final_Demo
{                                              comments in above program
  public static void main(String[] args)
  {
                                               are errors. Remove final
     bb b1 = new bb();
     b1.ainc();
                                               keyword from class than you
  }                                            will get error like final method
}
                                               can not be override.
                                                                        http://www.java2all.com
Method Overriding



                    http://www.java2all.com
Method overriding :


     Defining a method in the subclass that has the
same name, same arguments and same return type as
a method in the superclass and it hides the super class
method is called method overriding.

      Now when the method is called, the method
defined in the subclass is invoked and executed
instead of the one in the superclass.


                                            http://www.java2all.com
class Xsuper
{
   int y;
   Xsuper(int y)
   {
      this.y=y;
   }
   void display()
   {
      System.out.println("super y = " +y);
   }
}
class Xsub extends Xsuper
{
   int z;
   Xsub(int z , int y)
   {
      super(y);
      this.z=z;
   }
   void display()
   {
      System.out.println("super y = " +y);
      System.out.println("sub z = " +z);
   }
}

                                             http://www.java2all.com
public class TestOverride
{
  public static void main(String[] args)
  {
     Xsub s1 = new Xsub(100,200);
     s1.display();
  }
}

       Output :

       super y = 200
       sub z = 100




         Here the method display() defined in the
    subclass is invoked.
                                             http://www.java2all.com
Multi level Inheritance
class student
{
   int rollno;
   String name;
    student(int r, String n)
   {
      rollno = r;
      name = n;
   }
   void dispdatas()
   {
      System.out.println("Rollno = " + rollno);
      System.out.println("Name = " + name);
 } }
class marks extends student
{
   int total;
   marks(int r, String n, int t)
   {
      super(r,n); //call super class (student) constructor
      total = t;
   }
   void dispdatam()
   {
      dispdatas(); // call dispdatap of student class
      System.out.println("Total = " + total);
} }
                                                             http://www.java2all.com
class percentage extends marks
{
   int per;

  percentage(int r, String n, int t, int p)
  {
    super(r,n,t); //call super class(marks) constructor

  }
    per = p;                                                       Output :
  void dispdatap()
  {
    dispdatam(); // call dispdatap of marks class                  Rollno = 1912
    System.out.println("Percentage = " + per);
  }                                                                Name = SAM
}
class Multi_Inhe
                                                                   Total = 350
{                                                                  Percentage = 50
   public static void main(String args[])
   {
     percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage
     stu.dispdatap(); // call dispdatap of percentage class
   }
}




                                                                                       http://www.java2all.com
It is common that a class is derived from another
derived class.

      The class student serves as a base class for the
derived class marks, which in turn serves as a base
class for the derived class percentage.

      The class marks is known as intermediated base
class since it provides a link for the inheritance
between student and percentage.

     The chain is known as inheritance path.

                                              http://www.java2all.com
When this type of situation occurs, each subclass
inherits all of the features found in all of its super
classes. In this case, percentage inherits all aspects of
marks and student.

    To understand the flow of program read all
comments of program.

     When a class hierarchy is created, in what
order are the constructors for the classes that
make up the hierarchy called?

                                              http://www.java2all.com
class X
{
   X()
   {
     System.out.println("Inside X's constructor.");
   }
}
 class Y extends X // Create a subclass by extending class A.
{
   Y()
   {
     System.out.println("Inside Y's constructor.");
   }
}
class Z extends Y // Create another subclass by extending B.
{
   Z()
   {
     System.out.println("Inside Z's constructor.");     Output :
   }
}

{
 public class CallingCons
                                                        Inside X's constructor.
   public static void main(String args[])               Inside Y's constructor.
   {
     Z z = new Z();                                     Inside Z's constructor.
   }
}                                                                          http://www.java2all.com
The answer is that in a class hierarchy,
constructors are called in order of derivation, from
superclass to subclass.

      Further, since super( ) must be the first
statement executed in a subclass’ constructor, this
order is the same whether or not super( ) is used.

     If super( ) is not used, then the default or
parameterless constructor of each superclass will
be executed.

     As you can see from the output the
constructors are called in order of derivation.http://www.java2all.com
If you think about it, it makes sense that
constructors are executed in order of derivation.

       Because a superclass has no knowledge of any
subclass, any initialization it needs to perform is
separate from and possibly prerequisite to any
initialization performed by the subclass. Therefore, it
must be executed first.



                                              http://www.java2all.com
Dynamic Method Dispatch




                   http://www.java2all.com
Dynamic Method Dispatch:

      Dynamic method dispatch is the mechanism
by which a call to an overridden method is
resolved at run time, rather than compile time.

     Dynamic method dispatch is important
because this is how Java implements run-time
polymorphism.

      method to execution based upon the type of
the object being referred to at the time the call
occurs. Thus, this determination is made at run
time.                                          http://www.java2all.com
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 A
{
   void callme()
   {
     System.out.println("Inside A's callme method");
   }
}

class B extends A
{
     // override callme()
   void callme()
   {
     System.out.println("Inside B's callme method");
   }
}

class C extends A
{
     // override callme()
   void callme()
   {
     System.out.println("Inside C's callme method");
   }
}


                                                       http://www.java2all.com
public class Dynamic_disp
{
  public static void main(String args[])
  {
    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C
    A r; // obtain a reference of type A
    r = a; // r refers to an A object
    r.callme(); // calls A's version of callme
    r = b; // r refers to a B object
    r.callme(); // calls B's version of callme

        r = c; // r refers to a C object
        r.callme(); // calls C's version of callme
    }
}


                    Output :

                    Inside A's callme method
                    Inside B's callme method
                    Inside C's callme method
                                                     http://www.java2all.com
Here reference of type A, called r, is declared.

      The program then assigns a reference to each
type of object to r and uses that reference to invoke
callme( ).

      As the output shows, the version of callme( )
executed is determined by the type of object being
referred to at the time of the call.




                                              http://www.java2all.com
Abstract Classes



                   http://www.java2all.com
Abstract Classes :
     When the keyword abstract appears in a class
 definition, it means that zero or more of it’s methods are
 abstract.

     An abstract method has no body.

    Some of the subclass has to override it and provide the
 implementation.

     Objects cannot be created out of abstract class.

    Abstract classes basically provide a guideline for the
 properties and methods of an object.

                                                  http://www.java2all.com
•     In order to use abstract classes, they have to be
  subclassed.
•     There are situations in which you want to define
  a superclass that declares the structure of a given
  abstraction without providing a complete
  implementation of every method.
•     That is, sometimes you want to create a
  superclass that only defines generalized form that
  will be shared by all of its subclasses, leaving it to
  each subclass to fill in the details.
•     One way this situation can occur is when a
  superclass is unable to create a meaningful
  implementation for a method.
                                              http://www.java2all.com
Syntax :       abstract type name(parameter-list);

     As you can see, no method body is present.
Any class that contains one or more abstract methods
must also be declared abstract.

      To declare a class abstract, you simply use the
abstract keyword in front of the class keyword at the
beginning of the class declaration.

      There can be no objects of an abstract class.
That is, an abstract class cannot be directly
instantiated with the new operator.
                                              http://www.java2all.com
Any subclass of an abstract class must either
implement all of the abstract methods of the
superclass, or be itself declared abstract.




                                            http://www.java2all.com
abstract class A1
{
  abstract void displayb1();
  void displaya1()
  {
    System.out.println("This is a concrete method");
  }

}

class B1 extends A1
{
   void displayb1()
   {
     System.out.println("B1's implementation");
   }
}

public class Abstract_Demo
{
  public static void main(String args[])     Output :
  {
    B1 b = new B1();
    b.displayb1();
    b.displaya1();                           B1's implementation
  }
}                                            This is a concrete method
                                                                         http://www.java2all.com
Object Class



               http://www.java2all.com
The Object class :

      There is one special class, Object, defined by
Java. All other classes are subclasses of Object.

      That is, Object is a superclass of all other
classes.
      This means that a reference variable of type
Object can refer to an object of any other class.
Every class in java is descended from the
java.lang.Object class.

If no inheritance is specified when a class is defined,
the super class of the class is Object by default.
                                               http://www.java2all.com
EX :

       public class circle { ... }

       is equivalent to

       public class circle extends Object { ... }




                                               http://www.java2all.com
Methods of Object class
METHOD                                   PURPOSE

Void finalize()                 Called before an unused object is recycled

int hashCode( )                 Returns the hash code associated with the
                                invoking object.
void notify( )                  Resumes execution of a thread waiting on
                                the invoking object.
void notifyAll( )               Resumes execution of all threads waiting
                                on the invoking object.

String toString( )              Returns a string that describes the object.

void wait( )
void wait(long milliseconds) Waits on another thread of execution.
void wait(long milliseconds,
 int nanoseconds)                                    http://www.java2all.com
The methods notify(), notifyall() and wait() are
declared as final.

     You may override the others.
     tostring()
     ?public String tostring()

     it returns a String that describe an object.

     ?It consisting class name, an at (@) sign and
object memory address in hexadecimal.

                                              http://www.java2all.com
EX :

Circle c1 = new Circle();
System.out.println(c1.tostring());
It will give O/P like Circle@15037e5
We can also write System.out.println(c1);




                                            http://www.java2all.com
Polymorphism
Polymorphism :

     An object of a sub class can be used whenever
 its super class object is required.

 This is commonly known as polymorphism.

     In simple terms polymorphism means that a
 variable of super type can refer to a sub type
 object.
Inheritance chepter 7

More Related Content

What's hot

Inheritance
InheritanceInheritance
Inheritance
Tech_MX
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
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
 

What's hot (20)

Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Inheritance polymorphism-in-java
Inheritance polymorphism-in-javaInheritance polymorphism-in-java
Inheritance polymorphism-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
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance
InheritanceInheritance
Inheritance
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
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
 
Class and object
Class and objectClass and object
Class and object
 
javainheritance
javainheritancejavainheritance
javainheritance
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 

Similar to Inheritance chepter 7

SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
Abhishek Khune
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
mrecedu
 

Similar to Inheritance chepter 7 (20)

Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Core java day5
Core java day5Core java day5
Core java day5
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Presentation 3.pdf
Presentation 3.pdfPresentation 3.pdf
Presentation 3.pdf
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Keyword of java
Keyword of javaKeyword of java
Keyword of java
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
Unit3 java
Unit3 javaUnit3 java
Unit3 java
 
Inheritance
InheritanceInheritance
Inheritance
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Sdtl assignment 03
Sdtl assignment 03Sdtl assignment 03
Sdtl assignment 03
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 

More from kamal kotecha

Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
kamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

More from kamal kotecha (20)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Class method
Class methodClass method
Class method
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
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
 
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
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
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
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 

Inheritance chepter 7

  • 1. Chapter 7 Inheritance http://www.java2all.com
  • 2. Inheritance http://www.java2all.com
  • 3. What is a Inheritance ? • The derivation of one class from another class is called Inheritance. • Type of inheritance : http://www.java2all.com
  • 4. A A B B Single Inheritance A C Multi level Inheritance B C D Hierarchical Inheritance http://www.java2all.com
  • 5. • A class that is inherited is called a superclass. • The class that does the inheriting is called as subclass. • In above figure all class A is superclass. • A subclass inherits all instance variables and methods from its superclass and also has its own variables and methods. • One can inherit the class using keyword extends. Syntax : • Class subclass-name extends superclass-name • { // body of class. • } http://www.java2all.com
  • 6. In java, a class has only one super class. Java does not support Multiple Inheritance. One can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class can be a superclass of itself. http://www.java2all.com
  • 7. class A //superclass { int num1; //member of superclass int num2; //member of superclass void setVal(int no1, int no2) //method of superclass { num1 = no1; num2 = no2; } } class B extends A //subclass B { int multi; //member of subclass void mul() //method of subclass { multi = num1*num2; //accessing member of superclass from subclass } } Output : class inhe2 { public static void main(String args[]) { Multiplication is 30 B subob = new B(); subob.setVal(5,6); //calling superclass method throgh subclass object subob.mul(); System.out.println("Multiplication is " + subob.multi); } } http://www.java2all.com
  • 8. Note : Private members of super class is not accessible in sub class, super class is also called parent class or base class, sub class is also called child class or derived class. http://www.java2all.com
  • 9. Super & Final http://www.java2all.com
  • 10. Super
  • 11. super : super keyword is used to call a superclass constructor and to call or access super class members(instance variables or methods). syntax of super : super(arg-list) When a subclass calls super() it is calling the constructor of its immediate superclass. super() must always be the first statement executed inside a subclass constructor. super.member Here member can be either method or an instance variables. http://www.java2all.com
  • 12. This second form of super is most applicable to situation in which member names of a subclass hide member of superclass due to same name. http://www.java2all.com
  • 13. class A1 { public int i; A1() { i=5; } } class B1 extends A1 { int i; B1(int a,int b) { super(); //calling super class constructor //now we will change value of superclass variable i super.i=a; //accessing superclass member from subclass i=b; } void show() { System.out.println("i in superclass = " + super.i ); System.out.println("i in subclass = " + i ); } } public class Usesuper Output : { public static void main(String[] args) { B1 b = new B1(10,12); i in superclass = 10 b.show(); i in subclass = 12 } } http://www.java2all.com
  • 14. The instance variable i in B1 hides the i in A, super allows access to the i defined in the superclass. super can also be used to call methods that are hidden by a subclass. http://www.java2all.com
  • 15. Final http://www.java2all.com
  • 16. final keyword can be use with variables, methods and class. => final variables. When we want to declare constant variable in java we use final keyword. Syntax : final variable name = value; => final method Syntax : final methodname(arg) When we put final keyword before method than it becomes final method. http://www.java2all.com
  • 17. To prevent overriding of method final keyword is used, means final method cant be override. => final class A class that can not be sub classed is called a final class. A class that can not be sub classed is called a final class. This is archived in java using the keyword final as follow. Syntax : final class class_name { ... } Any attempt to inherit this class will cause an error and compiler will not allow it. http://www.java2all.com
  • 18. final class aa { final int a=10; public final void ainc() { a++; // The final field aa.a cannot be assigned } } class bb extends aa // The type bb cannot subclass the final class aa { public void ainc() //Cannot override the final method from aa { System.out.println("a = " + a); } } Here no output will be there because all the public class Final_Demo { comments in above program public static void main(String[] args) { are errors. Remove final bb b1 = new bb(); b1.ainc(); keyword from class than you } will get error like final method } can not be override. http://www.java2all.com
  • 19. Method Overriding http://www.java2all.com
  • 20. Method overriding : Defining a method in the subclass that has the same name, same arguments and same return type as a method in the superclass and it hides the super class method is called method overriding. Now when the method is called, the method defined in the subclass is invoked and executed instead of the one in the superclass. http://www.java2all.com
  • 21. class Xsuper { int y; Xsuper(int y) { this.y=y; } void display() { System.out.println("super y = " +y); } } class Xsub extends Xsuper { int z; Xsub(int z , int y) { super(y); this.z=z; } void display() { System.out.println("super y = " +y); System.out.println("sub z = " +z); } } http://www.java2all.com
  • 22. public class TestOverride { public static void main(String[] args) { Xsub s1 = new Xsub(100,200); s1.display(); } } Output : super y = 200 sub z = 100 Here the method display() defined in the subclass is invoked. http://www.java2all.com
  • 24. class student { int rollno; String name; student(int r, String n) { rollno = r; name = n; } void dispdatas() { System.out.println("Rollno = " + rollno); System.out.println("Name = " + name); } } class marks extends student { int total; marks(int r, String n, int t) { super(r,n); //call super class (student) constructor total = t; } void dispdatam() { dispdatas(); // call dispdatap of student class System.out.println("Total = " + total); } } http://www.java2all.com
  • 25. class percentage extends marks { int per; percentage(int r, String n, int t, int p) { super(r,n,t); //call super class(marks) constructor } per = p; Output : void dispdatap() { dispdatam(); // call dispdatap of marks class Rollno = 1912 System.out.println("Percentage = " + per); } Name = SAM } class Multi_Inhe Total = 350 { Percentage = 50 public static void main(String args[]) { percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage stu.dispdatap(); // call dispdatap of percentage class } } http://www.java2all.com
  • 26. It is common that a class is derived from another derived class. The class student serves as a base class for the derived class marks, which in turn serves as a base class for the derived class percentage. The class marks is known as intermediated base class since it provides a link for the inheritance between student and percentage. The chain is known as inheritance path. http://www.java2all.com
  • 27. When this type of situation occurs, each subclass inherits all of the features found in all of its super classes. In this case, percentage inherits all aspects of marks and student. To understand the flow of program read all comments of program. When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy called? http://www.java2all.com
  • 28. class X { X() { System.out.println("Inside X's constructor."); } } class Y extends X // Create a subclass by extending class A. { Y() { System.out.println("Inside Y's constructor."); } } class Z extends Y // Create another subclass by extending B. { Z() { System.out.println("Inside Z's constructor."); Output : } } { public class CallingCons Inside X's constructor. public static void main(String args[]) Inside Y's constructor. { Z z = new Z(); Inside Z's constructor. } } http://www.java2all.com
  • 29. The answer is that in a class hierarchy, constructors are called in order of derivation, from superclass to subclass. Further, since super( ) must be the first statement executed in a subclass’ constructor, this order is the same whether or not super( ) is used. If super( ) is not used, then the default or parameterless constructor of each superclass will be executed. As you can see from the output the constructors are called in order of derivation.http://www.java2all.com
  • 30. If you think about it, it makes sense that constructors are executed in order of derivation. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must be executed first. http://www.java2all.com
  • 31. Dynamic Method Dispatch http://www.java2all.com
  • 32. Dynamic Method Dispatch: Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. method to execution based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. http://www.java2all.com
  • 33. 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.
  • 34. class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } } http://www.java2all.com
  • 35. public class Dynamic_disp { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } } Output : Inside A's callme method Inside B's callme method Inside C's callme method http://www.java2all.com
  • 36. Here reference of type A, called r, is declared. The program then assigns a reference to each type of object to r and uses that reference to invoke callme( ). As the output shows, the version of callme( ) executed is determined by the type of object being referred to at the time of the call. http://www.java2all.com
  • 37. Abstract Classes http://www.java2all.com
  • 38. Abstract Classes : When the keyword abstract appears in a class definition, it means that zero or more of it’s methods are abstract. An abstract method has no body. Some of the subclass has to override it and provide the implementation. Objects cannot be created out of abstract class. Abstract classes basically provide a guideline for the properties and methods of an object. http://www.java2all.com
  • 39. In order to use abstract classes, they have to be subclassed. • There are situations in which you want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. • That is, sometimes you want to create a superclass that only defines generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. • One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. http://www.java2all.com
  • 40. Syntax : abstract type name(parameter-list); As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. http://www.java2all.com
  • 41. Any subclass of an abstract class must either implement all of the abstract methods of the superclass, or be itself declared abstract. http://www.java2all.com
  • 42. abstract class A1 { abstract void displayb1(); void displaya1() { System.out.println("This is a concrete method"); } } class B1 extends A1 { void displayb1() { System.out.println("B1's implementation"); } } public class Abstract_Demo { public static void main(String args[]) Output : { B1 b = new B1(); b.displayb1(); b.displaya1(); B1's implementation } } This is a concrete method http://www.java2all.com
  • 43. Object Class http://www.java2all.com
  • 44. The Object class : There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Every class in java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the super class of the class is Object by default. http://www.java2all.com
  • 45. EX : public class circle { ... } is equivalent to public class circle extends Object { ... } http://www.java2all.com
  • 46. Methods of Object class METHOD PURPOSE Void finalize() Called before an unused object is recycled int hashCode( ) Returns the hash code associated with the invoking object. void notify( ) Resumes execution of a thread waiting on the invoking object. void notifyAll( ) Resumes execution of all threads waiting on the invoking object. String toString( ) Returns a string that describes the object. void wait( ) void wait(long milliseconds) Waits on another thread of execution. void wait(long milliseconds, int nanoseconds) http://www.java2all.com
  • 47. The methods notify(), notifyall() and wait() are declared as final. You may override the others. tostring() ?public String tostring() it returns a String that describe an object. ?It consisting class name, an at (@) sign and object memory address in hexadecimal. http://www.java2all.com
  • 48. EX : Circle c1 = new Circle(); System.out.println(c1.tostring()); It will give O/P like Circle@15037e5 We can also write System.out.println(c1); http://www.java2all.com
  • 50. Polymorphism : An object of a sub class can be used whenever its super class object is required. This is commonly known as polymorphism. In simple terms polymorphism means that a variable of super type can refer to a sub type object.

Editor's Notes

  1. White Space Characters
  2. White Space Characters
  3. White Space Characters
  4. White Space Characters
  5. White Space Characters
  6. White Space Characters
  7. White Space Characters
  8. White Space Characters
  9. White Space Characters