by Dinesh Thakur

Inheritance is one the most powerful concepts in an object-oriented language. Through inheritance   the code developed for one class can be used in another class. That is, the data members made in a class can be used in another class. Inheritance is done by creating new classes that are extensions of other classes. The new class is known as a subclass. The original class is known as a superclass. The subclass has all the attributes of the superclass, and in addition has attributes that it defines itself. A class can have only one superclass. This is known as single inheritance. A superclass can have multiple subclasses.

Declaring Inheritance

A class inherits a super class with the help of keyword: extends

Syntax :

class classname extends anotherclass

{

... body of class

}

The extends keyword immediately follows the class name. It is followed by the name of the superclass from which this class will inherit characteristics. There can be only one class name following the extends keyword. Hence, inheritance provides a powerful mechanism for reusing existing code.

 

class Rectangle

          {
              int l,b;
             void Setval(int x,int y)
               {
                  l=x;
                  b=y;
               }
                   int GetRect()
                     {
                         return l*b;
                     }
           }
                     class Triangle extends Rectangle
                         {
                             int b,h;
                             float a;
                             void SetData(int v,int u)
                                 {
                                     b=u;
                                     h=v;
                                 }
                                     float GetTri()
                                        {
                                            a=(float)l/2*b*h;
                                            return (a);
                                        }
                          }
                                    class SingleInheritance
                                       {
                                            public static void main(String args[])
                                                {
                                                    Triangle Tri=new Triangle();
                                                    Tri.Setval(50,8);
                                                    Tri.SetData(17,7);
                                                    System.out.println("Area of Rectangle is :" +Tri.GetRect());
                                                    System.out.println("Area of Triangle is :"+Tri.GetTri());
                                                }
                                       }

Single Inheritance in Java Example