0% found this document useful (0 votes)
82 views

Inheritance Examples

Inheritance allows the creation of new classes from existing classes. The existing class is known as the parent/super class, while the new class is known as the child/derived class. There are different types of inheritance in Java including single, multilevel, hierarchical, and interface-based inheritance. Keywords like extends, super, and this are used for inheritance. extends is used to inherit from a parent class, super refers to parent class members, and this refers to current class members.

Uploaded by

Dar Vin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Inheritance Examples

Inheritance allows the creation of new classes from existing classes. The existing class is known as the parent/super class, while the new class is known as the child/derived class. There are different types of inheritance in Java including single, multilevel, hierarchical, and interface-based inheritance. Keywords like extends, super, and this are used for inheritance. extends is used to inherit from a parent class, super refers to parent class members, and this refers to current class members.

Uploaded by

Dar Vin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Inheritance :

Creating a new class from the existing class is known as inheritance.

Existing class -> Parent class / Super class


New Class -> Child class / Derived class

Usages :
1) Code reusability
2) Time saving

Types of inheritance :
1) Single inheritance (JAVA)
2) multiple inheritance (x)
3) multilevel inheritance (JAVA)
4) hierarchical inheritance (JAVA)
5) hybrid inheritance. (x)

Single Inheritance :
Only one parent , only one child.

Parent

Child

Multiple Inheritance :
Multiple parent , only one child
Multi level Inheritance :

Hiearchical Inheritance :

a
P
e
r
C
h
d
l
i n
t
1
2
3

Hybrid Inheritance :
itP
h
e
r
a C
1
2
3
ld
n
A class can be derived from another class, but class is a child of another.

Single parent, multiple child

Combination of other types.

Level 1

Level 2
Level 1

Level 2

Level 3
Class 3

Class 4

Note :

JAVA will not support multiple parents. So, here we can't use multiple and hybrid
inheritances. To overcome this problem, we can use interfaces.
How to Do inheritance :

extends -> is a keyword used to inherit

Syntax:
class parent
{
....
....
}
class child extends parent
{
......
.......
}

child c= new child();


c.functions

Inheritance Examples :
Example 1: (Single Inheritance)

Child Program:
import java.io.*;
classemp
{ intempno;
String ename,edept;
floatsal;
staticDataInputStream d = new DataInputStream(System.in);
void read() throws Exception // Member Functions
{
System.out.println("Enter the Employee details : ");
empno=Integer.parseInt(d.readLine());
ename=d.readLine();
edept=d.readLine();
sal=Float.parseFloat(d.readLine());
}
void display()
{
System.out.println("\nemployee Name : " + ename);
System.out.println("employee no : " + empno);
System.out.println("Department:"+edept);
System.out.println("Salary:"+sal);
}
public static void main(String arg[])throws Exception
{
emp e1= new emp();
e1.read();
e1.display();
}
}
Parent Program:
class employee extends emp
{
intacno;
String bname;
void get() throws Exception
{
read();
System.out.println("Enter Bank name and Account number :");
bname= d.readLine();
acno = Integer.parseInt(d.readLine());
}
voiddisp()
{
display();
System.out.println("Salary will be credited in");
System.out.println("\t Bank name & a/c. no.: " + bname + ", " + acno);
}
public static void main(String arg[]) throws Exception
{
employee e = new employee();
e.get();
e.disp();
}
}

Example 2: (Multilevel Inheritance)

class vehicle
{
String regno;
vehicle()
{
regno="TN 09 AX 6666";
}
}

class car extends vehicle


{
String cname, comp, color,make;
int model;
car()
{
cname="Scorpio";
comp="Mahendra";
color="Black";
make="India";
model=2019;
}
}
classLuxurycar extends car
{
String facilities;
Luxurycar()
{
facilities="A/C, DVD, LCD, Power window,.....";
}
void display()
{
System.out.println("Reg.No. : " + regno);
System.out.println("Carname : " + cname);
System.out.println("Company name : " + comp);
System.out.println("Color : " + color);
System.out.println("Year : " + model);
System.out.println("Make: " + make);
System.out.println("Facilities : " + facilities);
}

public static void main(String arg[ ])


{
Luxurycar l=new Luxurycar();
l.display();
}
}

Example 3: (Hierarchical inheritance )

import java.io.*;
class person
{
String name,gender;
int age;
DataInputStream d = new DataInputStream(System.in);
void read()throws Exception
{
System.out.println("Enter your name,gender and age : ");
name = d.readLine();
gender = d.readLine();
age = Integer.parseInt(d.readLine());
}

void display()
{
System.out.println("Name : " + name);
System.out.println("Gender : " + gender );
System.out.println("Age : " + age);
}
}

class student extends person


{
String course,duration;
float fee;
void read()throws Exception
{
System.out.println("Student Details: ");
super.read();
System.out.println("Enter Course name, duration and fee :");
course=d.readLine();
duration=d.readLine();
fee = Float.parseFloat(d.readLine());
}
void display()
{
super.display();
System.out.println("Course Details :\n\t" + course);
System.out.println("\t" + duration + "\n\t" + fee);
}
}

class patient extends person


{
String pbm,doc;
void read()throws Exception
{
System.out.println("Patient Details: ");
super.read();
System.out.println("Enter your problem and consulting doctor name : ");
pbm=d.readLine();
doc=d.readLine();
}

void display()
{
System.out.println("Patient Details :" );
super.display();
System.out.println("Problem : " + pbm);
System.out.println("Consulting Doctor: " + doc);
}
}

classmymain
{
public static void main(String arg[])throws Exception
{
patient p= new patient();
p.read();
p.display();

student s = new student();


s.read();
s.display();
}
}

Special Keywords in java:


/*
Special Keywords in Inheritance :
===============================
1) this keyword
2) super keyword
3) final keyword

This keyword :
---------------------
It is used to represent the current object's memory
Syntax:
this.member variable
this.member functions

Ex: 1
----------

classmyclass
{
int x=100; // Member variable
int y;
void display()
{
int x=10; // local variable
x=100; -> calls local variable
y=200; -> calls member variable
this.x=100; -> calls member variable
}
}
myclass m= new myclass();
m.x=200; -> member variable calling
*/
class product
{
String pname;
intqty;
float price;
product (String pname, intqty, float price)
{
this.pname=pname;
this.qty = qty;
this.price=price;
}
void display()
{
System.out.println("Product name : " + pname);
System.out.println("Quantity : " + qty);
System.out.println("Price : " + price);
}

public static void main(String arg[ ])


{
product p1= new product("bags",5,1200);
product p2= new product("shoe",5,1500);
p1.display();
p2.display();
}
}

super keyword:
============
It is used to represent the parent class's memory.
Syntax:
1) super ( ... ) -> to call parent class's constructor
2) super.variable -> to call variables from parent class
3) super.function() -> to call a function from parent class

Ex:1
------
class myclass1
{
int x, y;
myclass1()
{
x=100;
y=200;
}
}
class myclass2 extends myclass1
{
int x, y;
myclass2()
{
x=300;
y=400;
}
void display()
{
System.out.println("Parent...");
System.out.println("X= " + super.x);
System.out.println("Y= " + super. y);
System.out.println("Child...");
System.out.println("X= " + x);
System.out.println("Y= " + y);
}
public static void main(String arg[ ])
{
myclass2 m2= new myclass2();
m2.display();
}
}

Function overriding :
----------------------------
Parent and child class can have the same name of function with same
arguments, is known as function overriding.

It means, the child function will hide the parent's function


To call parent class function, we use 'super keyword'

Ex.2
======
class myclass1
{
void display()
{
System.out.println("Member function of Parent class");
}
}
class myclass2 extends myclass1
{
void display()
{
super.display();
System.out.println("Member function of Child class");
}
public static void main(String arg[ ])
{
myclass2 m2= new myclass2();
m2.display();
}
}

Ex: 3 Calling Super class constructor


---------

class class1
{
class1() // automatic 1st execution(parent)
{
System.out.println("Parent Constructor ");
}
}
class class2 extends class1
{
class2() // automatic 2nd execution (child)
{
System.out.println("child Constructor ");
}
public static void main(String arg[])
{
class2 c2= new class2(); // child class object creation
}
}

*/
class parent
{
int x, y;
parent (int a, int b)
{
x=a;
y=b;
}

void display()
{
System.out.println("x = " + x + "\n Y= " + y);
}
}

class child extends parent


{
int z;
child(inta,int b, int c)
{
super(a,b);// it should be a first line
z=c;
}
void display()
{
super.display();
System.out.println(" z = " + z);
}
public static void main(String arg[ ])
{

child c= new child (100,200,300);


c.display();
}
}
Final Keyword :
==============
1) To create a named constant.
Ex:
final float pi=3.14f;

2) To stop function overriding.


Ex
classmyparent
{
final void display()
{
System.out.println("Parent's function");
}
}

classmychild extends myparent


{
void display() // Error : cannot override
{
System.out.println("child's function");
}

public static void main(String arg[ ])throws Exception


{
mychild m=new mychild();
m.display();
m.display();
m.display();

}
}

3) To stop inheritance.
Ex:
*/

final class myparent


{
void display()
{
System.out.println("Parent's function");
}
}

classmychild extends myparent //Error : Cannot inherit


{
void display()
{
System.out.println("child's function");
}

public static void main(String arg[ ])throws Exception


{
mychild m=new mychild();
m.display();
m.display();
m.display();

}
}

You might also like