ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Inheritance

INHERITANCE

Inheritance is one of the key features of Java. Inheritance basic use is that it allows a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java is usually understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub class.
Purpose of Inheritance
1. To promote code reuse.
2. To use Polymorphism.

  1. class Parent
  2. {
  3. public void parent1()
  4. {
  5. System.out.println(“I am a Parent");
  6. }
  7. }
  8. public class Child extends Parent {
  9. public void child1()
  10. {
  11. System.out.println("I am a child");
  12. }
  13. public static void main(String[] args)
  14. {
  15. Child cobj = new Child();
  16. cobj.child1(); //method of Child class
  17. cobj.parent1(); //method of Parent class
  18. }
  19. }

Output
I am a Parent.
I am a child.

Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance

Example :

  1. class Fan
  2. {
  3. String FanType;
  4. }
  5. public class tablefan extends Fan {
  6.  
  7. String modelType;
  8. public void showDetail()
  9. {
  10. FanType = "tablefan"; //accessing Vehicle class member
  11. modelType = "equipment";
  12. System.out.println(modelType+" "+fanType);
  13. }
  14. public static void main(String[] args)
  15. {
  16. Fan fan =new Fan();
  17. Fan.showDetail();
  18. }
  19. }

Output
equipment tablefan

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!