inheritance – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Thu, 14 Mar 2024 16:53:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg inheritance – Programmerbay https://programmerbay.com 32 32 What Are the Five Main Features of OOPs? https://programmerbay.com/what-are-the-five-main-features-of-oops/ https://programmerbay.com/what-are-the-five-main-features-of-oops/#respond Wed, 13 Mar 2024 16:28:49 +0000 https://programmerbay.com/?p=5082 Object-Oriented Programming or OOPs is a programming paradigm that revolves around the concept of object, which contains properties and methods. 
It combines a group of related attributes and behaviour within a single unit named class, that enhances program design structure and code readability.
Further, it also resolves drawbacks of Procedural programming i.e  code complexity, unusable code.
 
Problem with Procedural Programming?
Procedural Programming follows top-down approach, meaning a program is viewed as a series of sequential steps.
In procedural programming, a program is divided into various procedures or functions which operate on data, the issue with this approach is, when the program grows larger, the code redundancy, maintainability, and complexity increases.
 
Both procedural and object-oriented are imperative programming.
 

Feature of OOPs

 
Object-Oriented programming focuses on binding attributes and behavior of a real-world entity represented using an object and supports features like abstraction, encapsulation, inheritance, and polymorphism. These are the following OOPs features.
  • Classes
  • Objects
  • Inheritance
  • Polymorphism
  • Data Abstraction and Encapsulation

Other OOPs Features:

  • Dynamic Binding
  • Message Passing

Here are the five main features of OOPs

Classes:

A class is the user-defined data type and the main building block of object-oriented programming.
It is an identifiable entity that can have some descriptive properties. It is a user-defined data type that holds data members and member functions in a single unit. It is like a blueprint of an object.
 
For example, consider an entity “Laptop” , what attributes, you can think of? RAM, OS, memory, manufacturer name, model name and so on.
 
public class Laptop
{
String modelName;
String manufacturerName;
String ram;
String memory;
String os;


void boot(){


}
}

The above code represents, how a laptop’s attributes and its behavior are put together in a single place.

Objects:

Objects are like a signature of a class. An object is an instance of a class without an object, no memory is allocated to a class’s data members or member function.
With an object of a class, we can access the data members and member functions that can be accessed (as per the private, public, protected accessibility scope).
 
An object represents a real-world entity, having a set of attributes and behavior. However, an object can’t be simply declared as same as primitive types.
 
Continuing Laptop’s example, we can define multiple Laptop objects and each object would get the same attributes and behavior declared in the respective class.
Laptop obj = new Laptop();
Laptop obj1 = new Laptop();
Laptop obj2 = new Laptop();

Initializing fields of a single object .

obj.modelName = " Pavilion 15";
obj.manufacturerName = "HP";
obj.ram = "4 GB";
obj.memory = "1 TB";
obj.os = "Windows";

Inheritance:

The ability to inherit the properties of one class to another, or inherit the properties from a base class to an inherited class is known as the concept of Inheritance.
With the help of inheritance, we can use the data members and member functions of a class to another.
 
  • It enables a class to acquire or get the properties from another class
  • It makes code reusable
  • It makes easier to add new features or methods to a class
  • It provides an overriding feature which allows a child class to have a specific implementation of a method defined in the parent class
 
A class that is inherited by other classes is termed as super class or parent class or base class, whereas a class that extends another class is termed as sub-class or child class
 
Features of Inheritance :
  • Code Reusability
  • Ease to add new feature
  • Overriding
 
Inheritance can be classified into majorly 5 types : Single Inheritance, Multilevel inheritance, Hierarchical Inheritance, Multiple Inheritance and Hybrid Inheritance
 
Syntax :
class Laptop extends Electronics
{


}

We can also control or check the data members and member functions to be accessed in the child classes by the means of access specifiers, types of inheritance, access specifiers, and their respective access will be discussed in later articles.

Polymorphism:

Polymorphism is best defined in one statement i.e., “Polymorphism means one name many forms”.
 
It can be best explained with an example with a comparison to C language; in C language there was one limitation that we can not use the already used function name, but C++ provides us a new feature of Polymorphism, by which we can use the same function name again and again with different signatures.
 
 
The in-depth topic of Polymorphism will be discussed in later articles.

Data Abstraction and Encapsulation:

 
Data Abstraction means hiding the background details and provide only essential details. one of the most common examples regarding this feature is Television, in television we control it with help of a remote and, know its external or the features to be used most whereas we don’t know the internal working of Television.
 
 
Encapsulation means binding up data under a single unit. A class is one of the main implementations of this concept. It can be viewed as a wrapper that restricts or prevents properties and methods from outside access. With the help of access modifiers such as private, protected, and public keywords, one can control the access of data members and member functions

Other OOPs Features:

Dynamic Binding:

Dynamic Binding which is also known as Late binding or run-time binding, is a process of executing the part of the code at runtime.
Sometimes we need to access some part at the runtime if we need then we can use this approach. We use virtual functions to achieve Dynamic Binding.

Message Passing:

In this, objects pass the message to each other in order to contact each other. Like when we want 2 or multiple objects to contact each other it is possible with the OOP.
 

Frequently Asked Questions

 

Q1. What is an object in OOPs?

An object can be viewed as a real-world entity which has attributes and behaviour. For example, a person, it can have attributes like name, age, gender and behaviour such as talking and walking. These properties are put together within a single unit named class. Therefore, an instance of a class is known as an object.

Q2. Which feature of oops is described as the reusability of code?

Inheritance is the feature of OOPs that describes the reusability of code. It provides the ability to inherit attributes and behaviours from one class to another class. A child class can access and use methods and fields of the parent class which leads to code reusability.


Q3. Which feature of oop is illustrated by function overloading?

Polymorphism is the feature of OOPs that is illustrated by function overloading or method overloading. Method overloading signifies a method having the same name can exhibit multiple functionalities based on its parameters.


Q4. Which two features of oops are the same?

Encapsulation and Abstraction are two features of OOPs that are the same. Encapsulation can manage accessibility and hide the attributes and behaviour of an object. In same way,  Abstraction represents only essential data to a user.


Q5. What are the basic principles of OOPs?

Encapsulation, Data Abstraction, Polymorphism and Inheritance are 4 basic principles of Object-Oriented Programming. They are also known as the four pillars of OOPs.

 

]]>
https://programmerbay.com/what-are-the-five-main-features-of-oops/feed/ 0
Multiple Inheritance in Java With Program Example https://programmerbay.com/multiple-inheritance-in-java-with-program-example/ https://programmerbay.com/multiple-inheritance-in-java-with-program-example/#respond Sat, 03 Feb 2024 16:27:51 +0000 https://programmerbay.com/?p=9046 In object-oriented programming (OOP), inheritance is a feature that allows a class or an interface to inherit attributes and behaviour from another class or interface. The class that is being inherited, is known as the parent class, while the class that inherits is termed as the child class.

In Java, inheritance can be implemented either through classes or interfaces. In the case of class, the parent class provides behavioural implementation (non-abstract method) that its child class acquires and reuses. But in the case of interfaces, the parent interface only supplies behavioural specification (abstract method) and the implementation is provided only when a class implements the interface.

Multiple Inheritance

Multiple Inheritance is a type of inheritance in which a class inherits more than one class. It may increase the complexity of a program as it can introduce deadly diamond or ambiguity problems. Apart from this, one also has to take care of special rules to prevent ambiguities, leading to extra efforts to deal with such cases.

multiple inheritance in Java

Therefore, unlike C++, Java doesn’t support multiple inheritance of implementation. As a result, a class cannot have more than one superclass or parent class. However, it does support this type of inheritance in the case of the interface. A basic construct, named interface, consists only of declaration, not implementation. Hence, an interface can inherit multiple interfaces.

multiple inheritance in java using interfaces

 

Syntax for multiple inheritance in Java :

interface A {
// members
}

interface B {
// members
}

interface C extends A, B{
// members
}

 

Ambiguity Problem or Diamond Problem in Java [Read more in brief : click here]

It is also known as the deadly diamond of death. This problem arises when a class acquires properties from multiple parent classes. For instance, suppose there are two classes, namely Person and Employee and both are having a common functionality getAge().

If a new class tries to inherit Programmer and Person at the same time, then it would automatically get getAge() method from both the parent classes. Further, the class would have two versions of getAge() with different implementations.

As a result, it would create ambiguity problem for the compiler, while identifying which version of getAge() to be selected – Person or Programmer.

This ambiguity or confusion is termed the diamond problem.

Therefore, Java doesn’t support multiple inheritance in classes.

Trying to Implement Multiple inheritance program in Java

As we know, multiple inheritance is not supported in the case of classes. It happens because two classes having the same method and different implementations can create ambiguity.

To check this on a programmatic level, we’ll be trying to implement the inheritance in form of a program.

Program:

class Employee {
    float salary;

// getting age of an employee
    int getAge(){
        return 21;
    }
}

class Person {
    String name;

    // getting age of a person
    int getAge(){
        return 23;
    }
}

// Trying to apply multiple inheritance by extending two class at time
class Programmer extends Employee,Person{

    public static void main(String[] args) {
        Programmer programmer = new Programmer();
        // Trying to get Age of a programmer
        System.out.println("Total salary for you programmer :: "+programmer.getAge());
    }
}

Error:

error: '{' expected
class Programmer extends Employee,Person{
                                 ^

Explanation:

  1. There are two classes named Person and Employee that have a common method getAge() in which each of them has their implementations
  2. When the Programmer class is trying to extend both the classes Person and Employee, a compile time exception is occurred

Multiple inheritance using interface in Java

Java doesn’t provide support for multiple inheritance of implementation ( non-abstract method or concrete class) but in the case of inheritance of interfaces or specifications (abstract methods), Java provides support for it.

It is because an interface can only provide only a declaration of a method, not implementation. As a result, when a class implements multiple interfaces and if a common method is available in those interfaces, it has to provide a single implementation which doesn’t create ambiguity.

An interface can have multiple parent interfaces at the same time. The functionality’s been demonstrated in the below example.

Java program to implement multiple inheritance using interface

Program:

interface Employee {
// getting age of an employee
    int getProgrammerAge();
}

interface Person {

    // getting age of a person
    int getProgrammerAge();
}
// Applying multiple inheritance by extending two interfaces at a time

interface Programmer extends Employee,Person{

    String getProgrammerName();
}

class Program implements Programmer{

    public static void main(String[] args) {
        Program code1 = new Program();
        // Trying to get Age of a programmer
        System.out.println("The code is written by :: "+code1.getProgrammerName()+" and age :: "+code1.getProgrammerAge());
    }

    @Override
    public int getProgrammerAge() {
        return 21;
    }

    // Overriding the method inherited from the interface
    @Override
    public String getProgrammerName() {
        return "Kui";
    }
}

Output:

The code is written by :: Kui and age :: 21

Explanation:

  1. In the above example, there are interfaces named Employee and Person.
  2. Both the interfaces is having abstract method getProgrammerAge(). Another interface Programmer is extending both of them, Employee and Person. And it also has a non-abstract method gerProgrammerName().
  3. As a result, the child interface has the access of getProgrammerAge() of both the parent interfaces.
  4. Now, the Program class has implemented the programmer interface. The class has provided implementation for both the methods gerProgrammerName() and getProgrammerAge().
  5. Since,  getProgrammerAge() was only a declaration, not implementation, it doesn’t matter, if two interfaces has the same method or not, at last they would be limited to declaration. The only part that differentiate them is implementation of the method, which is at the end provided by inheriting class.

The Solution of Diamond Problem

The default method that was introduced in Java 8, is the solution of the diamond problem or ambiguity problem. A default method is an implementation method within an interface. It is not mandatory for implementing classes to override it as its implementation is already provided by the interface.

It allows multiple inheritance to some extent. A default method with the same method name can be present in two or more interfaces. If a class implements them, then it would inherit properties of both.

In the case of default methods, Java defines a set of rules which needs to follow:
1) When a class overrides a default method of the implementing interface, then the class implementation would take the priority.

Example.

interface A {
    default void display() {
        System.out.println("I am a method from interface A");
    }
}

interface B {
    default void display() {
        System.out.println("I am a method from interface B");
    }

}

class C implements A,B{

    @Override
    public void display() {
        System.out.println("I am a method from class C");
    }

    public static void main(String[] args) {
        C obj = new C();
        obj.display();
    }
}

Output:

I am a method from class C

2) When a class doesn’t provide implementation, then an error would occur.

Example:

interface A {
    default void display() {
        System.out.println("I am a method from interface A");
    }
}

interface B {
    default void display() {
        System.out.println("I am a method from interface B");
    }

}

class C implements A,B{

    public static void main(String[] args) {
        C obj = new C();
        obj.display();
    }
}

Error:

error: types A and B are incompatible;
class C implements A,B{
^
  class C inherits unrelated defaults for display() from types A and B

3) If an interface is having a default method and is extended by another interface which consists same default method, then the most recent inheriting interface’s version in the hierarchy is considered.

Example.

interface A {
    default void display() {
        System.out.println("I am a method from interface A");
    }
}

interface B extends A {
    default void display() {
        System.out.println("I am a method from interface B");
    }

}

class C implements A,B{

    public static void main(String[] args) {
        C obj = new C();
        obj.display();
    }
}

Output:

I am a method from interface B

Java also allows the privilege to explicitly refer to a particular interface’s default implementation.

InterfaceName.super.methodName( )

 

]]>
https://programmerbay.com/multiple-inheritance-in-java-with-program-example/feed/ 0
Multilevel Inheritance in Java with Program Example https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/ https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/#respond Fri, 19 Jan 2024 14:08:35 +0000 https://programmerbay.com/?p=9054 Multilevel inheritance is a type of inheritance where a subclass acts as a superclass of another class. In other words, when a class having a parent class, is extended by another class and forms a sequential chain, then it’s termed Multilevel inheritance. For instance, class A is extended by class B, and further class B is inherited by class C which acquires features of class A and class B.

multilevel inheritance in Java

In multilevel inheritance, a parent can have a single child only and at least require three classes arranged sequentially, forming a chain of parent-child relations.

Syntax:

class A {

}

class B extends A {

}

class C extends B {

}

Multilevel inheritance program in Java

Below are some programs provided to implement multilevel inheritance in Java.

Example 1. Program to implement multilevel Inheritance in Java

Program:

class Person {

    String getName(){
        return "ProgrammerBay";
    }
}

class Programmer extends Person{
    String getCodingLanguage(){
        return "Java";
    }
}

class Program extends  Programmer{
    int getLineOfCode(){
        return 20;
    }
    public static void main(String[] args) {
        Program program = new Program();
        System.out.println(" I am "+program.getName()+" and I code in "+ program.getCodingLanguage()+
                " . This program has "+program.getLineOfCode()+" lines");
    }
}

Output:

I am ProgrammerBay and I code in Java . This program has 20 lines

Explanation:

In the above code, we are having 3 classes named Person, Programmer and Program where class Program is inheriting class Programmer, further, class Programmer is extending class Person. As a result, the Program class’s got the functionalities of class Programmer and also class Person.

Example 2. Program to show real world example of multilevel inheritance in Java

Program:

class iPhone6 {
    void makeCalls(){
        System.out.println("Calling functionality.......");
    }
}

// Getting feature of previous iPhone model
class iPhone10 extends iPhone6{

    void unlockPhoneByFaceId(){
        System.out.println("Unlocking phone by face Id.......");
    }

}
// Getting feature of previous iPhone10
class iPhone12 extends iPhone10{

    void supportFor5GNetwork(){
        System.out.println("5G network support.......");
    }

    public static void main(String[] args) {
        iPhone12 iPhone = new iPhone12();
        iPhone.makeCalls();  // feature reused of iPhone 6 for iPhone 12
        iPhone.unlockPhoneByFaceId(); // feature reused of iPhone 10 for iPhone 12
        iPhone.supportFor5GNetwork(); // additional feature
    }
}

Output:

Calling functionality.......
Unlocking phone by face Id.......
5G network support.......

Explanation:

In the above code, we’ve tried to explain multilevel inheritance using the iPhone Models example. Just similar to the previous example, iPhone12 class is having the functionality of iPhone10 and iPhone6 classes. Because iPhone12 class is inheriting iPhone 10 class, further, iPhone10 is extending iPhone 6 class.

Example 3. Program to print order of constructor calling using multilevel Inheritance in Java

Program:

class Person {
    Person(){
        System.out.println("This is Person's class constructor");
    }

    void printName(){
        System.out.println("ProgrammerBay");
    }
}

class Programmer extends Person{
    Programmer(){
        System.out.println("This is Programmer's class constructor");
    }
    void printCodingLanguage(){
        System.out.println("Java");
    }
}

class Program extends  Programmer{
    Program(){
        System.out.println("This is Program's class constructor");
    }

    void printLineOfCode(){
        System.out.println(20);
    }
    public static void main(String[] args) {
        Program program = new Program();
        program.printName();
        program.printCodingLanguage();
        program.printLineOfCode();
    }
}

Output:

This is Person's class constructor
This is Programmer's class constructor
This is Program's class constructor
ProgrammerBay
Java
20

Explanation:

  1. In the above code, there are three classes named Person, Programmer, Program declared in which Person is extended by Programmer and Programmer is further inherited by Program class.
  2. Each class’s got a default constructor, where we are printing a message to identify the order of invocation.
  3. When the program’s object got created, the very first block executed was the Person class, after the Programmer’s constructor was called and at last Program’s constructor.
  4. In other words, the constructor of the foremost class in the chain is invoked first, then the constructor of immediate next class is called one by one, until it invokes the constructor of the class whose object is created

Frequently Asked Questions

What is multilevel Inheritance in java?

Multilevel Inheritance in java can be defined as an inheritance where a class extends another class, and further, that subclass is become a parent of another class by extending it

How is multilevel Inheritance implemented in Java?

It can be implemented using extends keyword where class A is extended by B, and further, C sequentially extends B.

Is multilevel Inheritance allowed in Java?

Yes, multilevel Inheritance is supported in Java.

What are the types of Inheritance in Java?

There are various types of inheritance supported by Java.
In the case of interfaces, Java supports 5 types of inheritance
which are Single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance.
In the case of classes, it limits to 3 types which are single, multilevel and hierarchical inheritance as hybrid and multiple inheritance is not supported in this.

]]>
https://programmerbay.com/multilevel-inheritance-in-java-with-program-example/feed/ 0
Java Inheritance With Program Example https://programmerbay.com/java-inheritance-with-program-example/ https://programmerbay.com/java-inheritance-with-program-example/#respond Thu, 22 Sep 2022 19:50:53 +0000 https://programmerbay.com/?p=9032 Inheritance is an essential feature of object-oriented programming as it enables us to create and manage a hierarchy of classes. With the help of inheritance, a new class can acquire common attributes and behaviour from an existing class, which implies a class can reuse methods or fields of the superclass. Further, it can also have its own additional methods and fields. Inheritance represents the IS-A relationship.

In Java, a class that is inherited, is termed a superclass. The class that drives functionality from others is known as a subclass. As a result, the inheriting class can be viewed as an extended version of the parent class. It acquires all the members that are present in the superclass and use them accordingly.

The main advantage of inheritance is code reusability.
A parent class contains all the methods that are common in its children. On the other hand, a child class can have not only methods specific to itself, but also can acquire methods from the parent class using the inheritance .

Features of Inheritance in Java

  • Method Overriding: It allows us to redefine a parent class method in a child class having the same name and signature.
  • Code reusability: It avoids the need of rewriting the same functionality which is already defined in the existing class.
  • Minimise code duplication: Inheritance minimises code duplication.
  • Code conciseness: Code reusability implies the concise code structure of a program.

Syntax:

class A {
// body

}

class B extends A {


}

Program to implement inheritance in Java

Program:

class Parent {
    public void print() {
        System.out.println("Parent class !");
    }
}

class Child extends Parent {
    public void display() {
        System.out.println("Child class !");
    }

    public static void main(String[] args) {
        Child obj = new Child();
        obj.print();
    }
}

Explanation : 

In the above example, the Parent class is having print() method, and the child class is consisting a display() method only. Since the Child class is inheriting the Parent class, therefore, print() that belongs to the Parent class would become available for the Child class. As a result, Child class is having two methods, print() and display().

The inheritance concept implies that whatever members are present in the parent class, would automatically be available in the child class except for private members. This is how reusability works using the concept.

Types of Inheritance in Java

There are various types of inheritance supported by Java. However, when it comes to class, Java only provides support for three inheritance types, involving single, multilevel, and hierarchical inheritance. When it comes to interfaces, all 5 inheritance types are supported.

1. Single Inheritance : In this type of inheritance, single parent and child class are involved. When a class only inherits behaviour and attributes from a single existing class, then it is known as Single inheritance. For instance, class A extends class B, where class A is the only parent of class B and class B is the only child of class A.

In other words, a type of inheritance in which only a single subclass and parent class involve.

Single inheritance in Java

Syntax :

class A {

}

class B extends A {

}

Java program to implement single inheritance 

Program:

class College {

    void print(String name){
        System.out.println("This is MTech Student Name :: "+name);
    }
}

class Student extends College {
    String name;

    Student( String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Student student = new Student( "Pintu");
        student.print(student.name);
    }
}

Output:

This is MTech Student Name :: Pintu

2. Multiple inheritanceIn this type of inheritance, a single subclass class and multiple superclasses are involved. When a class extends multiple parent classes at a time then it is called multiple inheritance.

Java doesn’t provide support for multiple inheritance. However, it’s possible in case of interfaces.

 

multiple inheritance in Java

Syntax: 

interface A {

}

interface B {

}

interface C extends A,B{

}

Java program to implement multiple inheritance using interface

Program:

interface Practical {

    void printPracticalExaminationTime();
}

interface  Viva {

    void printVivaTime();
}

class Examination implements Practical, Viva{

    void printMarks(){
        System.out.println("10 Marks");
    }

    @Override
    public void printPracticalExaminationTime() {
        System.out.println("Practical examination will be at 9 AM");
    }

    @Override
    public void printVivaTime() {
        System.out.println("Viva examination will be at 12 PM");

    }

    public static void main(String[] args) {
        Examination obj = new Examination();
        obj.printPracticalExaminationTime();
        obj.printVivaTime();
        obj.printMarks();
    }
}

Output:

Practical examination will be at 9 AM
Viva examination will be at 12 PM
10 Marks

3. Multilevel InheritanceIn this type of inheritance, three or more classes are involved. When a class inherits an existing class, and that subclass further gets extended by another class, it is called multilevel inheritance. For instance, class C inherits class B, and class B inherits class A, forming a sequential chain, it is called multilevel inheritance.

multilevel inheritance in Java

Syntax:

class A {


}

class B extends A {


}

class C extends B {

}

Java Program to implement multiple inheritance

Program:

class Person {

    String getName(){
        return "ProgrammerBay";
    }
}

class Programmer extends Person{
    String getCodingLanguage(){
        return "Java";
    }
}

class Program extends  Programmer{
    int getLineOfCode(){
        return 20;
    }
    public static void main(String[] args) {
        Program program = new Program();
        System.out.println(" I am "+program.getName()+" and I code in "+ program.getCodingLanguage()+
                " . This program has "+program.getLineOfCode()+" lines");
    }
}

Output:

I am ProgrammerBay and I code in Java . This program has 20 lines

4. Hierarchical InheritanceIn this type of inheritance, single parent and multiple child classes are involved. When a single class gets inherited by two or more classes at a time, it is known as hierarchical inheritance. In Java, a parent class can have multiple subclasses. For instance, there are 4 classes, A, B, C, D class,if class A is extended by B, C and D, then it would be said hierarchical inheritance .

Hierarchical Inheritance in Java

Syntax: 

class A {

}

class B extends A {

}

class C extends A {

}

class D extends A {

}

Java Program to implement hierarchical inheritance

Program:

class Shape {

void printArea(long area) {
System.out.println("Area = " + area);
}
}

class Square extends Shape {

long calculateArea(long side) {
return side * side;
}
}

class Rectangle extends Shape {

long calculateArea(long l, long b) {
return l * b;
}

public static void main(String[] args) {
long area;
Square squareObj = new Square();
Rectangle rectangleObj = new Rectangle();
area = squareObj.calculateArea(3);
squareObj.printArea(area);
area = rectangleObj.calculateArea(3, 2);
rectangleObj.printArea(area);

}
}

Output:

Area = 9
Area = 6

 

5. Hybrid Inheritance:In this, a combination of various inheritance types is involved. When classes inherit one another in a way that the hierarchy structure consists of two or more types of inheritance. In other words, it can be defined as an inheritance where two or more types of inheritance are used together

Hybrid Inheritance in Java

Syntax :

class A {

}

class B extends A {

}

class C extends B {

}
class D extends B {

}

Java Program to implement hybrid inheritance

Program:

public class A {
    public void display() {
        System.out.println("I am a method from class A");
    }
}

class B extends A {
    public void print() {
        System.out.println("I am a method from class B");
    }
}

class C extends B {
    public void show() {
        System.out.println("I am a method from class C");
    }
}

class D extends C {
    public void show() {
        System.out.println("I am a method from class D");
    }
    public static void main(String[] args) {
        D objD = new D();
        objD.display(); // A is indirect parent of D, therefore, the display method gets inherited all the way to leaf
    }
}

Output:

I am a method from class A

Important aspects of Inheritance :

The inheritance hierarchy works from parent to child only. In other words, a child can have members of its parent class, but it’s not possible in the case of a parent to have members of child class.

Case 1: Can parent class reference variable invoke method of child class?

No, it’s not possible. Inheritance follows parent to child relationship, vice versa is not allowed.

However, it can only access overridden method of child class.

Case 2. Can parent class reference variable hold instance of child class?

Yes, a parent reference variable can hold object of child class. Although, it is not able to call child methods, it’ll only work with parent members and overridden methods.

Program example :

class Person {

    void display(){
        System.out.println("Parent class method");
    }

    void show(){
        System.out.println("Parent show method");
    }
}

class Programmer extends Person{
    void print(){
        System.out.println("Child class method");
    }

    @Override
    void show() {
        System.out.println("Child show method");
    }

    public static void main(String[] args) {

        Person programmer = new Programmer();
        programmer.display();  // Only parent class method is accessible, not child class
        programmer.show();  // Runtime polymorphism comes into picture, able to access child class method 
    }
}

Case 3. Can child reference variable hold object of parent class?

No, it’s not possible. The JVM compilers would trigger an Incompatible type exception. Consider the above example, All Programmers can be a person, but every person can’t be a Programmer. In a nutshell, it would violate is-a relationship.

Why Java doesn’t provide support for multiple inheritance?

In the case of classes, the multiple inheritance concept is not supported in Java. Java doesn’t allow a class to extend multiple classes at a time, otherwise, compile time error would occur.

irect 12

The reason is the ambiguity problem. When two classes have the same method and are inherited by a class, that method became available for the inheriting class. As a result, it creates ambiguity or confusion for the compiler in determining which method to call at runtime. In other words, when a compiler can’t be able to resolve the method call at the time of program execution due to duplicate behaviour generated from multiple inheritance,then it is termed an ambiguity problem or diamond can access problem.

Why Java supports multiple inheritance in case of interfaces, but not in case of classes?

An interface can have public and abstract members. It consists only declaration of a method but not its actual definition. Therefore, When two interfaces having the same method declaration, are inherited by a child interface or directly implemented by a class doesn’t create an ambiguity issue as the definition or implementation of that method is only possible through a class.

The ambiguity problem only arises when two or more implementations of the same methods are exist. In the case of interfaces, there can always be the single implementation provided through the inheriting class as interfaces are only capable of method declarations, not implementation.

]]>
https://programmerbay.com/java-inheritance-with-program-example/feed/ 0
Hierarchical Inheritance in Java with program Example https://programmerbay.com/hierarchical-inheritance-in-java-with-program-example/ https://programmerbay.com/hierarchical-inheritance-in-java-with-program-example/#respond Mon, 19 Sep 2022 16:15:17 +0000 https://programmerbay.com/?p=9057 Hierarchical inheritance is a type of inheritance in which two or more classes inherit a single parent class. In this, multiple classes acquire properties of the same superclass. The classes that inherit all the attributes or behaviour are known as child classes or subclass or derived classes. The class that is inherited by others is known as a superclass or parent class or base class. For instance, class B, class C, and class D inherit the same class name.

Hierarchical Inheritance in Java

Syntax :

class A {

}

class B extends A {

}

class C extends A {

}

Hierarchical Inheritance Programs in Java

In order to implement hierarchical inheritance, we need to ensure at least two classes inherit the same parent class.

Example 1.  Java Program to implement Hierarchical Inheritance

Program:

public class A {
    public void display() {
        System.out.println("I am a method from class A");
    }
}

class B extends A {
    public void print() {
        System.out.println("I am a method from class B");
    }
}

class C extends A {
    public void show() {
        System.out.println("I am a method from class C");
    }
}

class D extends A {
    public void outPut() {
        System.out.println("I am a method from class D");
    }

    public static void main(String[] args) {
        B objB = new B();
        C objC = new C();
        D objD = new D();
        objB.display();
        objC.display();
        objD.display();
    }
}

Output:

I am a method from class A
I am a method from class A
I am a method from class A

Explanation:

  1. In the above example, we are having four classes namely A, B, C and D
    Class B, C, and D are inheriting the same class named A.
  2. We’ve declared and initialized objects of B, C and D to demonstrate that all has the access of display() functionality of parent class A.
  3. Lastly, we are simply printing output from display() method using B, C, and D object

Example 2.  Java Program to calculate the salary of an Employee using Hierarchical Inheritance

Program:

public class Employee {
    int baseSalary;
    Employee(){
        this.baseSalary = 50000;
    }
}

class TempEmployee extends Employee{
    float incrementPercent;

    TempEmployee(){
        this.incrementPercent = 0.1f;
    }

}

class PermanentEmployee extends Employee{
    float incrementPercent;

    PermanentEmployee(){
        this.incrementPercent = 0.2f;
    }

    public static void main(String[] args) {
        TempEmployee tempEmployee = new TempEmployee();
        PermanentEmployee permanentEmployee = new PermanentEmployee();

        System.out.println("Total salary of Temporary Employee :: "+ ((tempEmployee.baseSalary * tempEmployee.incrementPercent) + tempEmployee.baseSalary));
        System.out.println("Total salary of Permanent Employee :: "+ ((permanentEmployee.baseSalary * permanentEmployee.incrementPercent) + permanentEmployee.baseSalary));
    }
}

Output:

Total salary of Temporary Employee :: 55000.0
Total salary of Permanent Employee :: 60000.0

Explanation:

  1. In the above example, we are having three classes named Employee, TempEmployee, and PermanentEmployee
  2. Class TempEmployee and PermanentEmployee are extending the Employee class. As a result, both classes have access to the baseSalary field of the Employee class.
  3. We are simply creating objects of TempEmployee and PermanentEmployee classes. Both objects have initialized with some default bonus percentage value via the constructor
  4. Based on bonusPercentage and basicSalary fields, we are calculating and printing the salary of both types of employees.

]]>
https://programmerbay.com/hierarchical-inheritance-in-java-with-program-example/feed/ 0
Hybrid Inheritance in Java with Program Example https://programmerbay.com/hybrid-inheritance-in-java-with-program-example/ https://programmerbay.com/hybrid-inheritance-in-java-with-program-example/#respond Mon, 19 Sep 2022 15:50:50 +0000 https://programmerbay.com/?p=9061 Hybrid inheritance is a type of inheritance in which two or more variations of inheritance are used. For instance, suppose, there are various classes namely A, B, C, D and E. if class A gets extended by class B, then this would be an example of Single inheritance. Further, if class C, D and E extend class B,then it would be an example of hierarchical inheritance. In this manner, multiple types of inheritance can be used within the same hierarchy structure, that is termed Hybrid inheritance.

Hybrid Inheritance in Java

 

Hybrid Inheritance Programs in Java

Hybrid inheritance can be implemented using combination of single, multilevel, and hierarchical inheritance. Below is a simple example for the same.

Example 1. Java program to implement Hybrid Inheritance with the help of single and hierarchical inheritance

Program:

public class A {
    public void display() {
        System.out.println("I am a method from class A");
    }
}

class B extends A {
    public void print() {
        System.out.println("I am a method from class B");
    }
}

class C extends B{
    public void show() {
        System.out.println("I am a method from class C");
    }
}

class D extends B{
    public void show() {
        System.out.println("I am a method from class D");
    }
}

class E extends B {
    public void outPut() {
        System.out.println("I am a method from class E");
    }

    public static void main(String[] args) {
        E objE = new E();
        objE.display(); // A is indirect parent of E, therefore, the display method gets inherited all the way to leaf
    }
}


Output:

I am a method from class A


Explanation:

  1. Class A and B are depicting the implementation of single inheritance as class B is inheriting class A where class A is a parent and class B is its single child
  2. Further, classes B, C, D and E are resembling the implementation of hierarchical inheritance as class B is being extended by C, D and E.
  3. Lastly, E has got access to class A’s method named display() indirectly through B. And we’ve used the display() method to print the output.

Example 2. Java program to implement Hybrid Inheritance with the help of multilevel and hierarchical inheritance

Program:

public class A {
    public void display() {
        System.out.println("I am a method from class A");
    }
}

class B extends A {
    public void print() {
        System.out.println("I am a method from class B");
    }
}

class C extends B {
    public void show() {
        System.out.println("I am a method from class C");
    }
}

class D extends C {
    public void show() {
        System.out.println("I am a method from class D");
    }
}

class E extends C {
    public void outPut() {
        System.out.println("I am a method from class E");
    }

    public static void main(String[] args) {
        E objE = new E();
        objE.display(); // A is indirect parent of E, therefore, the display method gets inherited all the way to leaf
    }
}

Output:

I am a method from class A


Explanation:

  1. In this example, classes A, B and C are depicting the implementation of multilevel inheritance as class A is being extended by class B and further, class B is being aquired by C.
  2. Further, classes C, D and E are providing the implementation of hierarchical inheritance as class C is being extended by D and E.
  3. Lastly, E can access class A’s method named display() through C and B. And we’ve used the method to print the output.
]]>
https://programmerbay.com/hybrid-inheritance-in-java-with-program-example/feed/ 0
Why Multiple Inheritance is Not Supported in Java https://programmerbay.com/why-multiple-inheritance-is-not-supported-in-java/ https://programmerbay.com/why-multiple-inheritance-is-not-supported-in-java/#respond Fri, 26 Aug 2022 07:34:33 +0000 https://programmerbay.com/?p=5824 In this article, we’ll be discussing what is use of inheritance and why multiple inheritance is not supported in Java .

One of the main features of object-oriented programming is Inheritance. In Java, Inheritance can be defined as a way by which a class acquires properties from another class.

A class which inherits properties from another class is known as subclass or child class, while the class which is inherited, is termed as superclass or parent class. extends keyword is used in order to inherit the properties of another class.

Syntax:

class SubClass extends ParentClass { 
// Attributes and behavior 
}

As and when, a class uses extends keyword, it can access and include all data members and member functions of the inherited class . However, a child class can never access and inherit the private members of parent class.

Why we use Inheritance in Java ?

Inheritance provides a number of features:

  •  Code Reusability:

Code reusability means an existing class can be reused in other class, specifically for similar type of classification.

  • Ease to add new feature:

One can provide new functionality to a new class by using the existing class without changing it.

  • Overriding

This provides the freedom of having methods with the same signature as in parent class but with meaningful implementation.

Why Multiple Inheritance is Not Supported in Java?

Multiple Inheritance is a type of inheritance in which a class extends two or more classes.
Unlike C++, Java doesn’t support multiple inheritance.

The reason because multiple inheritance raises ambiguity problem which creates the possibility of inheriting multiple copies or generating multiple paths of same data for child class.

In other words, a compiler can’t able to determine which member to choose if inheriting classes have common members. This problem is termed as Diamond Problem.

image 2020 12 27 141335
Figure: Diamond Problem in Inheritance

 

For example, suppose a class represents Person having getGender() method and this Person Class is inherited by Man and Woman Class. Since both have inherited getGender() method from Person Class.

However, if Man and Woman Class is further extended by another class named Programmer. As a result, the Programmer Class would get two copies of “getGender()” method which leads to ambiguity for compiler. Meaning, a compiler won’t be able resolve method call at runtime.

Program to show the concept of Inheritance

class A
{
int a;
A() // constructor
{
a=10;
}
void display() // method
{
System.out.println("I am here with "+ a);
}
}

class B extends A{ // inheriting
void show()
{
display();
}
}
public class Inheritanceuseing {
public static void main(String[] args) {
B obj = new B();
obj.show();
}

}

]]>
https://programmerbay.com/why-multiple-inheritance-is-not-supported-in-java/feed/ 0
Difference between this and super keywords in Java? https://programmerbay.com/difference-between-this-and-super-keywords-in-java/ https://programmerbay.com/difference-between-this-and-super-keywords-in-java/#respond Thu, 16 Jan 2020 16:49:31 +0000 https://programmerbay.com/?p=5886 Java provides two useful implicit reference variables ‘this’ and ‘super’. Both are used to resemble the reference variable pointing to the superclass or subclass.

Both keywords are frequently used and if you want to read them thoroughly links are provided here. ( for ‘this’ keyword and for ‘super’ keyword).

The basic difference between this and super is that this reference variable is of subclass type, whereas super reference variable is of superclass type

Difference between this and super keywords in Java

'this' keyword'super' keyword
this keyword is an implicit reference variable ( that holds physical address of an object) that is used to refer current class objectssuper keyword is an implicit reference variable ( that holds physical address of an object) that is used to refer child class's immediate parent class objects
It invokes the constructor of subclass It invokes the constructor of superclass
In the case of the overridden methods( a method which is present in both parent and child with the same signature but with meaningful implementation), 'this' keyword is used to invoke the method of subclass classIn the case of the overridden method( a method which is present in both parent and subclass with the same signature but with meaningful implementation), 'super' keyword is used to invoke the method of superclass
It solves the problem of variable hiding. Using 'this' keyword, a compiler always refers to instance variable of the current classUsing super keyword, compiler always refer to immediate parent class instance variable ( in case of a variable having the same name in parent and subclass)
It can be used to return and pass as an argument in context of current class objectIt can be used to return and pass as an argument in context of parent class object

This keyword

In Java, this keyword is used to refer to the current class object.

There are various situations where sometimes is important to mention the object that actually invoked a particular method, constructor and initialization of instance variable. It can be used to invoke current class constructor, method, instance variable and many more.

Example of ‘this’ keyword

class sample1{
int m;
int n;

sample1()
{
m=5;
n=10;
}

void display()
{
System.out.println(" Value of M = "+m+" Value of N = "+n);
}
}

class sample extends sample1{
int x;
int y;
sample(int a,int b)
{
x=a;
y=b;

}
void callchecker()
{
this.display();
}
@Override
void display()
{
System.out.println(" Value of x = "+x+" Value of Y = "+y);
}
}
public class ThisKeyword {
public static void main(String[] args) {
sample obj = new sample(10,20);
obj.callchecker();
}

}

Super keyword

In Java, super keyword is used to refer to the parent class object. It deals with various situation, but the most importantly, it helps in resolving the name conflict between member variables of superclass and subclass having same name.

Example of ‘super’ keyword

class A 
{ 
int z; 
A(int a) {
 z=a; 
}
 public void f1() { } 
}
 class B extends A
 {
 int z;
 B(int a, int b) 
{
 super(a); //call for super class constructor
 z=b; 
} 
public void f1() 
{
 super.f1(); //call for super class method 
} 
public void f2() {
 super.z=4; //call for super class variable 
} } 
public class Example { 
public static void main(String[] args)
 { 
B obj = new B(); 
B obj = new B(5,3); 
obj.f1(); 
obj.f2(); 
} }

]]>
https://programmerbay.com/difference-between-this-and-super-keywords-in-java/feed/ 0