Inheritance:
- It is the process of joining two or more classes and we can access the values from both classes.
Types of Inheritance:
1) Single inheritance
2) Multilevel inheritance
3) Hierarchical inheritance
4) Hybrid inheritance
Benefits of inheritance:
- Software re-usability
- Information hiding
- Code sharing
Syntax:
class a
{
//Base class
}
class b extends a
{
//Derived class
}
Object creation:
Derived_class_name object_name =new derive_class_name();
object_name.function(parameter list); //If use constructor then NO need this
Example:
import java.util.Scanner;
class item // Base class
{
String
item_name;
int qty;
float
price;
double
amt;
Scanner
sc = new Scanner(System.in);
item()
//Constructor
{
System.out.println("Enter item name : ");
item_name = sc.next();
System.out.println("Enter number of quantity : ");
qty =
sc.nextInt();
System.out.println("Enter item price : ");
price
= sc.nextFloat();
amt =
qty * price;
}
}
class display extends item // Derived class
{
display()
{
System.out.println("\nOutput of Item details with total
amount........... ");
System.out.println("Item name : " + item_name);
System.out.println("Quantity : " + qty);
System.out.println("Item price : " + price);
System.out.println("Total amout : " + amt);
}
}
public class Constructor_with_inheritance {
public
static void main(String args[]) {
display d = new display();//Object
}
}
Output:
No comments:
Post a Comment