Java OPP Programming 7
Java OPP Programming 7
Java OPP Programming 7
IS-A RELATIONSHIP
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs.
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.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
SALAR FADHIL 73
INHERITANCE IN JAVA
THE SYNTAX OF JAVA INHERITANCE
class Subclass-name extends Superclass-name{ class Employee{
//methods and fields float salary = 40000;
} }
class Programmer extends Employee{
int bonus = 10000;
In the example, Programmer object can public static void main(String args[]){
access the field of own class as well as of
Employee class i.e. code reusability. Programmer p = new Programmer();
SALAR FADHIL 76
INHERITANCE IN JAVA
TYPES OF INHERITANCE IN JAVA
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance.
SALAR FADHIL 77
INHERITANCE IN JAVA
SINGLE INHERITANCE EXAMPLE
creating a subclass from a single superclass is called class Animal{
single inheritance. In single-level inheritance, there is only void eat(){
one base class and can be one derived classes. System.out.println(“Animal eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println(“Dog barking...");
}
}
class SingleInheritance {
public static void main(String args[]){
Dog d = new Dog();
d.bark();
Output:
d.eat();
Dog barking...
} Animal eating...
}
SALAR FADHIL 78
class ChwarGosha{
int x;
void calcChwar(int la){
INHERITANCE IN JAVA x = la;
SINGLE INHERITANCE EXAMPLE }
System.out.println("robare chwar gosha : "+x * x);
class SingleInheritance{ }
static int num1 = 10; class Lakesha extends ChwarGosha {
static int num2 = 5; int y;
}
void calcLakesha(int la1, int la2){
class MainInheritance extends SingleInheritance{ x = la1;
y = la2;
public static void main(String[ ] args){ System.out.println("robare lagesha : "+ x * y);
}}
int num3 = 2; class SingleInheritance_3{
int result = num1 + num2 + num3; public static void main(String[ ] args) {