Lec15 Inheritance-1
Lec15 Inheritance-1
The process of creating the new class by using the existing class functionality called as
Inheritance.
Inheritance simply means reusability.
It is called as - (IS Relationship)
Why ?
The idea behind inheritance in Java is that you can create new classes , that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Example- IS Relationship
Class Policy {
}
Class TermPolicy extends Policy {
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
Note-
All the parent members are derived into child class but they are depends upon the below
-To check the access specifiers
-Members does not exist into sub class.
Confidential
UML Diagram-
Parent -P
Child – C
Note-
When to use?
Business requirement-
Why inheritance?
Suppose we have one class which contain the fields like, firstname, lastname, address, city,
mobile number and
In future we got the requirement to add the PAN number then what option we have below-
1. Modify the attributes/fields in existing class but this is not good option it will increase the
testing for that class.
Confidential
2. Add the attributes in the new class, in this the good option we can also reduce the testing
efforts for this.
Class Parent {
String firstname;
String lastname;
String address;
String city;
String mobilenumber;
}
Class Child extends Parent {
String pancard;
Note
Dynamic dispatch-
The process of assigning the child class reference to parent class called as “Dynamic dispatch.”
Example-
Class X {
Confidential
}
Class Y extends X {
}
Class Test {
Public static void main(string args[]){
X x= new Y(); // Here we are assigning the child reference new Y() to parent class .
}
Inheritance Example-
Scenario 1
package com.inheritance;
class X {
int a = 10;
int b = 20;
void m1() {
System.out.println("Class X- m1() method");
}
void m2() {
System.out.println("Class X- m2() method");
}
}
package com.inheritance;
class Y extends X {
int b = 30;
int c = 40;
Confidential
void m2() {
System.out.println("Class Y- m2() method");
}
void m3() {
System.out.println("Class Y- m3() method");
}
}
package com.inheritance;
//Scenario- 1
X x=new X();
System.out.println(x.a);
System.out.println(x.b);
System.out.println(x.c);
x.m1();
x.m2();
x.m3();
//Scenario-2
Y y = new Y();
System.out.println(y.a);
System.out.println(y.b);
System.out.println(y.c);
y.m1();
y.m2();
y.m3();
//Scenario-3
Confidential
X x = new Y();
System.out.println(x.a);
System.out.println(x.b);
//System.out.println(x.c);
x.m1();
x.m2();
//x.m3();
y.m2();
y.m3();
Confidential