![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
In single inheritance, one new class accesses the properties (fields and methods) of one old class.
Consider an example of Bank. The bank contains all the basic details which are required to show to the users. When a new account is created then that account will automatically get the basic bank details from the bank instead of creating by user. Which saves the user time
See below program to understand Single Inheritance
Develop a program for bank which contains two classes bank and user. The Bank is the Base class and User is the Derived class. Use the bank class data to display user details of bank using Single inheritance
import java.util.Scanner; class Bank { Scanner sc = new Scanner(System.in); String bank_name,branch,name; int acc_no,balance,contact_no; Bank() { bank_name = "National Bank"; branch = "London"; } void getDetails() { System.out.println("Enter name, account no and contact no : "); name = sc.next(); acc_no = sc.nextInt(); contact_no = sc.nextInt(); } void displayDetails() { System.out.println("\nName : "+name); System.out.println("Account NO : "+acc_no); System.out.println("Contact NO : "+contact_no); } } class User extends Bank { public static void main(String args[]) { User u1,u2; u1 = new User(); u2 = new User(); u1.getDetails(); u2.getDetails(); System.out.println("Bank Name : "+u1.bank_name); System.out.println("Branch Name : "+u1.branch); u1.displayDetails(); u2.displayDetails(); } }
Output
While in Inheritance, when we create an object of Derived class then Base class
Default Constructor is executed first instead of Derived Class Default constructor. This is because of the highest priority of Base class constructor