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

PPTX
Inheritance in java
PPT
Java Programming - Inheritance
PPT
Java: Inheritance
PPTX
Java inheritance
PPS
Interface
PPTX
Inheritance in java
PPTX
Inheritance
PPTX
Inheritance in Java
Inheritance in java
Java Programming - Inheritance
Java: Inheritance
Java inheritance
Interface
Inheritance in java
Inheritance
Inheritance in Java

What's hot (20)

PPTX
Java Inheritance
PPTX
Dynamic method dispatch
PPT
Inheritance polymorphism-in-java
PPTX
Java Inheritance - sub class constructors - Method overriding
PDF
itft-Inheritance in java
PPT
Inheritance in java
PPTX
Inheritance In Java
PDF
Inheritance In Java
PPTX
Inheritance ppt
PPTX
Multiple inheritance possible in Java
PPTX
Inheritance
PDF
java-06inheritance
PPSX
Seminar on java
PPT
Java inheritance
DOCX
JAVA Notes - All major concepts covered with examples
PPTX
Class and object
PDF
javainheritance
PPTX
Ppt on this and super keyword
PPTX
Inheritance in Java
Java Inheritance
Dynamic method dispatch
Inheritance polymorphism-in-java
Java Inheritance - sub class constructors - Method overriding
itft-Inheritance in java
Inheritance in java
Inheritance In Java
Inheritance In Java
Inheritance ppt
Multiple inheritance possible in Java
Inheritance
java-06inheritance
Seminar on java
Java inheritance
JAVA Notes - All major concepts covered with examples
Class and object
javainheritance
Ppt on this and super keyword
Inheritance in Java
Ad

Similar to Inheritance chepter 7 (20)

PPTX
Basics to java programming and concepts of java
PDF
Java Basic day-2
PPTX
Inheritance Slides
PPT
Core java day5
PPTX
Chap-3 Inheritance.pptx
PPTX
inheritance and interface in oops with java .pptx
PPTX
Inheritance & interface ppt Inheritance
PPTX
Object Oriented Programming Inheritance with case study
PPTX
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
PPT
Lecture 14 (inheritance basics)
PDF
Java kkdhaksndjsjkanshdjdjdnsnxxhjdjdnxhxjx
PPTX
Modules 333333333³3444444444444444444.pptx
PPTX
Unit3 inheritance
PPT
RajLec10.ppt
PPT
Java inheritance
PDF
Presentation 3.pdf
PDF
Inheritance and interface
PPTX
Module 3 and 4-javahjhhdhdhddhhdhdhdhd.pptx
PDF
java_inheritance.pdf
DOCX
Keyword of java
Basics to java programming and concepts of java
Java Basic day-2
Inheritance Slides
Core java day5
Chap-3 Inheritance.pptx
inheritance and interface in oops with java .pptx
Inheritance & interface ppt Inheritance
Object Oriented Programming Inheritance with case study
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
Lecture 14 (inheritance basics)
Java kkdhaksndjsjkanshdjdjdnsnxxhjdjdnxhxjx
Modules 333333333³3444444444444444444.pptx
Unit3 inheritance
RajLec10.ppt
Java inheritance
Presentation 3.pdf
Inheritance and interface
Module 3 and 4-javahjhhdhdhddhhdhdhdhd.pptx
java_inheritance.pdf
Keyword of java
Ad

More from kamal kotecha (20)

PPS
Java Hibernate Programming with Architecture Diagram and Example
PPTX
Network programming in java - PPT
PPT
Java servlet life cycle - methods ppt
PPS
Java rmi example program with code
PPS
Java rmi
PPS
Jdbc example program with access and MySql
PPS
Jdbc api
PPS
Jdbc architecture and driver types ppt
PPS
Java Exception handling
PPS
JSP Error handling
PPS
Jsp element
PPS
Jsp chapter 1
PPS
String and string buffer
PPS
Wrapper class
PPS
Packages and inbuilt classes of java
PPS
Class method
PPS
Introduction to class in java
PPS
Control statements
PPTX
Jsp myeclipse
PPTX
basic core java up to operator
Java Hibernate Programming with Architecture Diagram and Example
Network programming in java - PPT
Java servlet life cycle - methods ppt
Java rmi example program with code
Java rmi
Jdbc example program with access and MySql
Jdbc api
Jdbc architecture and driver types ppt
Java Exception handling
JSP Error handling
Jsp element
Jsp chapter 1
String and string buffer
Wrapper class
Packages and inbuilt classes of java
Class method
Introduction to class in java
Control statements
Jsp myeclipse
basic core java up to operator

Recently uploaded (20)

DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
My India Quiz Book_20210205121199924.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
20th Century Theater, Methods, History.pptx
PPTX
Computer Architecture Input Output Memory.pptx
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PDF
IGGE1 Understanding the Self1234567891011
PDF
Empowerment Technology for Senior High School Guide
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Complications of Minimal Access-Surgery.pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Uderstanding digital marketing and marketing stratergie for engaging the digi...
My India Quiz Book_20210205121199924.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
Environmental Education MCQ BD2EE - Share Source.pdf
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
LDMMIA Reiki Yoga Finals Review Spring Summer
20th Century Theater, Methods, History.pptx
Computer Architecture Input Output Memory.pptx
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
What if we spent less time fighting change, and more time building what’s rig...
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
IGGE1 Understanding the Self1234567891011
Empowerment Technology for Senior High School Guide
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Complications of Minimal Access-Surgery.pdf

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

  • #18: White Space Characters
  • #19: White Space Characters
  • #20: White Space Characters
  • #27: White Space Characters
  • #32: White Space Characters
  • #33: White Space Characters
  • #37: White Space Characters
  • #45: White Space Characters
  • #46: White Space Characters