Sunday 26 October 2014

Inheritance in java

00:11 Posted by Unknown No comments

Inheritance :

Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
Using inheritance you can create general class that defines common set of related items.This class can be inherited by other classes.
In the terminology of java  , a class that is inherited is called "superclass" and the class that does inheriting called as "subclass".

Note : - 

In Java, only si.ngle inheritance is allowed and thus, every class can have at most one direct superclass. A class can be derived from another class that is derived from another class and so on. Finally, we must mention that each class in Java is implicitly a subclass of the Object class.

By "extends" keyword we can implement inheritance in java.

Example of inheritanc

class A
{
          //members of class A
}
class B extends A
{
          //members of class A inherited into B
           // members of class B
}

The private members of the superclass that cannot be accessed directly from the subclass. Also, constructors are not members, thus they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Simple example of inheritance

class Animal
{
     public Animal()
    {
               System.out.println("Animal created........");
    }
    public void sleep()
   {
         System.out.println("Animal sleep........");
    }
}
class Horse extends Animal
{
     public Horse()
    {
               System.out.println("Horse created........");
     }
      //Horse class inherits sleep() method from Animal class
}
public class MainClass
{
                 public static void main(String[] args)
                {
                    Animal animal=new Animal();   //Animal class Object created
                    Horse horse=new Horse();       // Horse class Object created
                   animal.sleep();
                    horse.sleep();   
                }
}

OUTPUT

Animal created........
Animal created........
Horse created........
Animal sleep........ Animal sleep........

The inheritance in Java provides the following features:

1.You can declare new fields in the subclass that are not in the superclass.
2.You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
3.You can declare new methods in the subclass that are not in the superclass.

0 comments :

Post a Comment