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