Tuesday 7 February 2017

Components of Inheritance in Java


                                                      
Components of Inheritance in Java


Method Overriding

When a method in a subclass has the same name and type signature as a method in its superclass , then the method in the subclass is said to override the method in the superclass.

When an overriden method is called from within the subclass , it will always refer to the version of that method defined by the subclass.The version defined by superclass will be hidden.

Program:                       //Method overriding
                        class A
         {
              int i,j ;
        A(int a , int b)
            {
                i=a;
                j=b;
            }
       void show()
     {
           System.out.println(" i and j=" + i  +" " + j);
      }
}
                  class B extends A
   {
            int k;
           B( int a , int b , int c)
           {
                super(a,b);
                 k=c;
            }
           void show( )
        {
            System.out.println("k=" + k);
        }                                                                 Output:
 }                                                                             k=9
               class OverrideDemo
 {
       public static void  main ( String [] args )
     {  
               B b= new B ( 2,3,4);
               b.show( );
       }
 }
  

Abstract Classes


Abstract keyword can be used with both class_name and  method_name. An abstract class will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method.

The subclass should  override all necessary methods.We can also specify the method of superclass as abstract. Such methods must be overriden by the following subclass's.

The general form is :

    abstract type name ( parameters_list);

The members of abstract class cannot be accessed via new operator but are instead accessed via reference variables.

Program:           //abstract demonstration
                     abstract class A
      {
              abstract void callme ( );
               
              void callMetoo ( )
            {
              System.out.println(" This is a concrete method");
            }
   }
                 class B extends A
    {
          void callme ( )
         {
            System.out.println ( " B's implementation of callme");
          }
    }
               class AbstractDemo
    {
         public static void main ( String [] args )
     {
           B b = new B ( );
           b.callme () ;
           b.callMetoo();
     }
 }


In order to prevent method overriding , we use final keyword  before the declaration.


                                                                           By: Knowledge Bits


              
       

No comments:

Post a Comment

Video of the Day

Contact us

Name

Email *

Message *