Inheritance
Inheritance is a process or a mechanism where one class acquire the properties which include methods and fields of another class. With the use of this concept the information is made manageable in a hierarchical order.
The class which inherits the properties of another class is known as subclass or derived class or child class. and the class whose properties are inherited is called as base class or parent class.
In java inheritance cannot be achieved until we use extends keyword.
Reason to use Inheritance
1 For Method overriding
2 For code reusability
Syntax:
class abc {
.........
.........
}
class xyz extends abc {
.........
.........
}
----------------------------------------------------------------------------------------------------------------------------
Example
//WAP to Demonstrate Inheritance.............
import java.io.*;
class Superclass
{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
Double num1,num2;
void get()
{
try
{
System.out.print("Enter the 1st number:- ");
num1=Double.parseDouble(r.readLine());
System.out.print("Enter the 2nd number:- ");
num2=Double.parseDouble(r.readLine());
}
catch(Exception ex)
{
}
}
void put()
{
System.out.println ("1st number:- "+num1);
System.out.println ("2nd number:- "+num2);
}
}
class Subclass extends Superclass
{
Double num3;
void display()
{
num3=num1*num2;
System.out.println ("Multiplication = "+num3);
}
}
class single2
{
public static void main (String[] args) {
Subclass s1= new Subclass();
s1.get();
s1.put();
s1.display();
}
}
Output
Enter the 1st number:- 12
Enter the 2nd number:- 2
1st number:- 12.0
2nd number:- 2.0
Multiplication = 24.0
----------------------------------------------------------------------------------------------------------------------------
Types of Inheritance
1 Single inheritance
2 Multilevel inheritance
3 Hierarchical inheritance
Single inheritance
In single inheritance a single class is inherited from the base class.
Multilevel inheritance
In multilevel inheritance a class is derived from a class which is derived from the base class
Hierarchical inheritance
when more than one class is inherited from the base class is called as hierarchical inheritance.
👍👍👍
ReplyDeleteNice 👍
ReplyDeleteAaaaaaaaa kharach ky
ReplyDeleteHelpful blog sir
ReplyDeleteThank you
DeleteVery helpful information sir,
ReplyDeletePlease regularly update the vlog
You provide very easy solution and your blogs are really awesome
Thank you sir for such important information
ReplyDeleteThanku sir
ReplyDelete