Monday, March 23, 2015

What is an Inheritance?






  What is an Inheritance?



The derivation of one class from another class is called Inheritance.

A class that is inherited is called a super class.

The class that does the inheriting is called as subclass.

A subclass inherits all instance variables and methods from its super class and also has its own variables and methods.

One can inherit the class using keyword extends.

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 super class of another subclass.

However, no class can be a super class of itself. 



 Why use Inheritance?



For Method Overriding (So Runtime Polymorphism). 

For Code Reusability




Syntax:-



Class subclass-name extends super class-name
{
        // body of class.
}



Example of inheritance





 Example of inheritance 


Programmer is the subclass and Employee is the super class. Relationship between two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.


         class Employee
{
          int salary=40000; //member of super class
}
class Programmer extends Employee
{
         
int  bonus=10000; //member of subclass
Public Static void main(String args[])
{
Programmer p=new Programmers;
System.out.println(”Programmer salary is: “+ p.salary);
System.out.println(“Bonus of Programmer is: “+ p.bonus);
                   }
          }

Ø  Output:

Programmer salary is: 40000
Bonus of Programmer
is:10000



Note: Private members of super class is not accessible in subclass, super class is also called parent class or base class, Subclass is also called child class or derived class.





Example of inheritance




v  Types of Inheritance:-
      
1) Single

2) Multilevel

3) Hierarchical 


ð  Note: Multiple inheritance is not supported in java in case of class.
ð  When a class extends two classes known as multiple inheritance.






Why multiple inheritance is not supported in java?


ð  To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

ð  For Example:

class Tester
{
void msg()
{
                    System.out.println(”Hello”);     
}
}
class Programmer
{
          void msg()
          {
                   System.out.println(“Welcome”);
          }
}
class Company extends Tester, Programmer
{
          public static void main(String args[])
          {                
                    Company obj=new Company();
                    obj.msg;    //Now which msg() method would be invoked?
          }
}


0 comments:

Post a Comment