Why inheritance is needed in java with examples ?

How to define inheritance in Java ?

Inheritance is very important part of OOPs concept in JAVA.In simple words, Inheritance can be defined as the mechanism in which one class inherit the property of another class.The subclass will have  state and behavior of super class along with its own.

  • Inheritance defines IS-A relationship between super class and sub class.

Why Inheritance is needed in JAVA?

  • To obtain the reusability of code thus reducing redundant code.
  • To obtain the extensibility of code i.e. to have the ability to extend new functionality with minimal change.

How to use inheritance in Java for code reusability ?

  • Inheritance can be obtained in java using extend keyword in JAVA.
For example- class A extends B{

}

where A is subclass and B is the superclass.Class A is inheriting the property of class B.

Example:

In below example sub class SamsungNote inherit the super class SamsungGalaxy so SamsungNote will have all the property of  SamsungGalaxy.So method present in SamsungGalaxy is available in SamsungNote.

Code reusability in Java using inheritanceSamsungGalaxy .java

public class SamsungGalaxy {
public void exchangeInfo(){
System.out.println("Exchange Info");
}
public void sendSms(){
System.out.println("Send Msg");
}
}

SamsungNote.java

public class SamsungNote extends SamsungGalaxy {
public void sendMms(){
System.out.println("Send MMS");
}
public void playVideo(){
System.out.println("PLAY VIDEO");
}

}

MobileInherit.java

public class MobileInherit {

public static void main(String[] args) {
SamsungNote mobile=new SamsungNote();
mobile.exchangeInfo();
mobile.playVideo();
mobile.sendMms();
mobile.sendSms();

}

}


OUTPUT:

Exchange Info
PLAY VIDEO
Send MMS
Send Msg

Points to remember in Java inheritance


1-Multilevel Inheritance is also possible i.e. Class B extends Class A and Class C extends class B then Class C will have state and behavior of Class A and Class B.

2-Multiple Inheritance is not possible in JAVA i.e. Class C can not extend Class A and class B both.

Let us understand why multiple inheritance is not possible in JAVA.
Assume Class C extends both and Class A and Class B. Class A and Class B have a common method play(); . Now if we call method play(); on the object of Class C it will create confusion that which play() method to invoke Class A or Class B.To avoid this confusion JAVA does not support multiple inheritance.

3-private members of Super class are not inherited.

Hope you like this post.

You may be interested in Best Practices in Java
Give you suggestion in comments.If you like the post Share with your friends on social network.








Why inheritance is needed in java with examples ? Why inheritance is needed in java with examples ? Reviewed by JavaInstance on 12:17:00 PM Rating: 5

No comments:

Powered by Blogger.