Professional Documents
Culture Documents
:8
Aim: To Write Java Program on inheritance
.
Theory:
Inheritance in Java
It is the mechanism in java by which one class is allowed to inherit the features(fields and
methods) of another class.
• Super Class: The class whose features are inherited is known as superclass(or a base class
or a parent class).
• Sub Class: The class that inherits the other class is known as a subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we
can derive our new class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Types of Inheritance in Java
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance: In single inheritance, subclasses inherit the features of one superclass.
Algorithm:
Step 1: Start
Step 9: call the methods read(),deposit(),withdraw(),display() for objects of current class and
saving account.
Step 10:Stop
Program(Code):
import java.util.*;
class bank
{
protected String name;
protected int acc_no;
protected String type;
protected boolean cheque;
protected float penalty;
protected float min_balance;
protected float balance;
protected float interest;
}
class current_acc extends bank
{
public void read()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Name,account no.,penalty,minimum balance and opening
balance=balance+balance*interest;
System.out.println("Interest Added");
}
}
class account
{
public static void main(String[] args)throws Exception
{
int n,i;
current_acc c =new current_acc();
c.read();
c.deposit(10000);
c.withdraw(2000);
c.display();
savings_acc s =new savings_acc();
s.read();
s.deposit(10000);
s.withdraw(2000);
s.display();
}
}
Output:
/*
D:\programs>javac account.java
D:\programs>java account
Enter Name,account no.,penalty,minimum balance and opening balance of the curren
t account holder:
sachin
151
2000
1000
10000
Account Details:
Name:sachin
Account no:151
Balance:18000.0
Cheque book facility:true
Enter Name,account no.,interest rate and opening balance of the savings account
holder:
samar
2001
9
60000
Account Details:
Name:samar
Account no:2001
Balance:68000.0
Cheque book facility:false
D:\programs>
Outcome: with this we/student will able to use property of resability through inheritance t in the
java program.