Inheritance In Java And Types Of Inheritance With Examples

Inheritance in Java:

Java arranges types in hierarchical relations in which they are actual Type-of-relationships. A newly declared class extended by the keyword extends another class. It will then be Subclass (also subclass, child class, or extension class)). The class from which the subclass inherits is called the upper class (also superclass or parent class). By Java, the Inheritance mechanism will display all visible properties of the upper class to the lower class. So an upper class inherits properties, and the subclass inherits them.

  • Inheritance: Inheritance in Java means that you have a new class to an existing class. So take over the entire class with all the methods and only add or modify the functions for your application.

Inheritance Syntax in java

The syntax for java Inheritance is very simple:

class B extends A {

// … New Class B Code

}

This means that all non-private methods and fields are in a new class B Class A. In B, further methods and fields. In the example above, A is the base class. Depending on which literature you are is also of the inheriting class, the superclass, the upper class, or the parent class. B is typically referred to as a derived or extended class. Other common terms are subclass, child class, and subclass. Unlike some other programming languages (especially C++) does not support multiple inheritances. A new class Z may so do not inherit from X and Y at the same time. class Z extends X, so Y not allowed. On the other hand, an inheritance in several Steps: X is the base class, Y inherits from X, and Z inherits from Y, etc.



Why is redundancy in code bad?

Instead of working with inheritance or interfaces, the temptation is often large, existing code is easily converted into a new class and there. This is quick and requires little Thought effort. Redundant code has two major drawbacks: The maintenance effort for your entire project increases, e.g. with extensions. In addition, errors in code must now be placed in several locations that are correct. This is often forgotten or leads to consequential errors.

Override methods:

Java allows you to override methods of inheritance. Implement for this Simply reuse the method in question. You only need to ensure that the parameter list, return value, and access modifiers exactly match the original method. Optionally, you can prefix the annotation @Override to the new method. This explicitly tells the compiler that the following method overrides a method of the upper class. That gives allows the compiler to check this. If you have a typing error or the parameter list does not match the original method, the compiler will return an error message.

To emphasize it again: @Override is not required to perform a Method to overwrite. The annotation serves only as a hedge, that no error occurs when overwriting.

What are annotations?

Annotations make it possible to add metadata to the source text. Some annotations pass the information on to the compiler; other annotations are adopted unchanged in the bytecode. The metadata can then be evaluated by other Java tools or through the reflection classes. Internally in Java, annotations are a special form of interfaces. Annotations are always preceded by the @ sign. Annotations are given in front of all modification keywords of an element, often on a line of its own. In addition to the @Override annotation just mentioned, the Practice most often come into contact with @Deprecated. Some Classes and methods from the Java standard library that are have proven to be faulty or at least not optimal so marked. They can still be used, the Java However, developers explicitly advise against it. Both the Java compiler and the Eclipse also display corresponding warnings.


The power of Inheritance in java:

Output:

inheritance in java

BoxWeight inherits all the properties of Box and adds the weight component to them. BoxWeight does not need to recreate all the functions contained in the Box. It can be a box to fulfill its own purposes. A great advantage of inheritance is that you have created a superclass that defines You can create as many more specific objects as you want using the attributes that are common to a set of objects Subclasses. Each subclass can customize its own classification.

Remember, once you’ve created an upper class that defines the general aspects of an object, this superclass can be inherited to form specialized classes. Any subclass simply adds its own unique attributes. This is the essence of inheritance.


A superclass variable can reference a subclass object

The reference variable of an upper class can be assigned a reference to any subclass derived from This superclass. You will find this aspect of inheritance very useful in a variety of situations. For example, consider the following:

Output:

inheritance in java

Here, weightbox is a reference to BoxWeight objects and box2 is a reference to Box objects. Because BoxWeight is a subclass of Box, it is allowed to assign a reference to the Weight box object. It is important to understand that this is the type of the reference data variable, not the type of object it refers to determines which members can be accessed. That is if a reference to a subclass object is assigned to an overclass reference variable. You have access only to the parts of the object defined by the upper class. Therefore, box2 cannot access its Weight, even if it refers to a BoxWeight object. If you think about it, it makes sense. because the upper class doesn’t know what a lower class adds to it. Therefore, the last line of code in the preceding fragment has been commented out. A box reference is not possible to access the weight field because the box does not define any.

Using super in java inheritance:

In the previous examples, classes derived from Box were not as efficient or implemented as robust as they could have been. i.e, the constructor for BoxWeight explicitly Initializes the box width, height, and depth fields (). This not only duplicates the code found in its upper class(or superclass), which is inefficient but implies that a subclass must be granted access to those members. However, there will be times when you want to create a superclass that retains the details of its implementation (i.e. it keeps its data members private). In this case, there is no way for a subclass to directly access or initialize these variables alone. Since encapsulation is a primary attribute of OOP, it isn’t astounding that Java gives an answer to this issue. Whenever a subclass has to refer to its immediate upper class (or Superclass), it can do this with the keyword super. Super has two general forms. The first calls the constructor of the upper class. The second is used to access a member of the upper class that was hidden by a member of a lower class. Every use is investigated here.



Using Super to Call Superclass Constructors

A subclass can call a constructor defined by its upper class by using the following form of super:

Super(arg-list);

Here, arg-list specifies all the arguments that the constructor requires in the upper class. super () must always be the first statement executed in a constructor of a subclass. Consider this improved version of the BoxWeight () class to see how super () is used:

As you can see above, BoxWeight () calls super () with the arguments w, h, and d. As a result, the box () Constructor to call that initializes width, height, and depth with these values. BoxWeight no longer initializes these values itself. Only the unique value must be initialized in addition: Weight. This allows Box to make these values private if desired. In the previous example, super () was called with three arguments. The designer can be overloaded, super () can be called with any shape defined by the upper class. The executed constructor corresponds to the arguments. For example, here is a Full implementation of BoxWeight, which provides constructors for various options that a box can be built. In any case, super () is called with the corresponding arguments. Note that width, height, and depth have been privatized in Box.

Example: how to use super in java inheritance:

Output:

inheritance in java

Note that super () will pass an object of type BoxWeight – not of type Box. The rest calls the Constructor Box (Box ob). As already mentioned, a superclass variable can be is used to reference an object derived from this class. So we can pass a box weight Object to the box constructor. Of course, Box only knows its own members. Let’s look at the key concepts behind super (). When a subclass calls super (), it calls the constructor of its immediate upper class. Thus super () always refers to the upper class immediately above the calling class. This also applies in a multi-level hierarchy. Also, super () must always be the first statement executed in a subclass constructor.


Final Classes and Methods:

If you declare a class final, it cannot be inherited in the following. Alternatively, you can mark methods of a class as final; in this case, the class may be inherited as such; the method in question may not be overridden.

In practice, final classes are used when the developers consider that further modification of the class is not appropriate, for example, because it threatens the consistency of a library. The most famous example of a final class in the standard Java library is String.

Super Keyword:

The super keyword is like this keyword. Following are where the super keyword is utilized.

  • Utilize to differentiate the members of the superclass from the members of the subclass, in the event that they have the same names.
  • utilize to invoke the superclass constructor from subclass

Abstract Classes:

Within a class, one or more methods can be abstracted as are marked. The methods concerned are then only, but not equipped with code. Instead of The code of the method placed in brackets simply follows a semicolon. Once there is even one abstract method, the entire class can be marked as abstract! Abstract classes can be are not used directly, i.e. it is impossible to use new AbstractClass() to create an object (instance). The benefits of abstract classes consist of providing a foundation for further, derived classes.

There are countless abstract examples in the standard Java library classes. For example, java.io.Reader is an abstract class that provides basic functionality for reading files. To which derived classes include BufferedReader, StringReader, and InputStreamReader.

If you derive your own class from an abstract class, you must implement all abstract methods (unless your class is also abstract).


Generalization

Once inheritance is involved, it is your turn to declare variables the choice of whether to use the object variable directly with the type of the respective Declare class or more generally with the type of the base class. Both variants can be useful, depending on whether you want it goes to use specific methods of a certain class, or else about generally processing several objects of a base class. To illustrate the concept of generalization, let us assume that four classes are defined – A, B, C1, and C2:

Now we define four object variables, all of type A. Save in them we object of classes A, B, C1, and C2. With getClass () you can create a class Determine the object that contains the exact description of the class including the Contains class name.

The following lines show the possibilities and limits of generalization. For example, the call to obj3.x1() or obj4.x2() is not is permissible. For the Java compiler, obj3 and obj4 are class A variables, and this class does not know the methods x1 and x2. However, it is possible to assign obj to a new variable obj of type C . (This assignment only works because obj3 is actually an object of the Class C1 contains!) Now the method call x1() works. Another approach would be an explicit casting. The preceding (C2) makes it clear to the compiler that it has obj4 as an object of class C2 treatment. This allows calling x2. The casting works of course only if obj4 really contains an object of class C2; otherwise, an error occurs at run time.

Example: how to inherits the attributes and methods from derived class (subclass) into base class(superclass):

Output:

inheritance in java



Types of Inheritance in java:

Single Inheritance in java:

In single inheritance, subclasses inherit the characteristics of an upper class. In the figure below, class A serves as the base class for derived class B.

Single inheritance flowchart:

inheritance in java

Example: how to use single inheritance in java:

output:

inheritance in java

Multiple Inheritances in java:

Java does not support multiple inheritances. Java supports multiple inheritances through the interface.


Multilevel Inheritance in java:

To this point, we have used simple class hierarchies that consist of only one upper class (or superclass) and a subclass. However, you can create hierarchies that contain as many inheritance levels as possible as you like. As already mentioned, it is quite acceptable to use one subclass as the upper class of another. For example, if three classes are named A, B, and C, C can be a subclass of B, which is a Subclass of A. When this type of situation occurs, each subclass inherits all characteristics in all his upper classes. In this case, C inherits all characteristics of B and A. To see how A multi-level hierarchy can be useful. Consider the following program. In it, the subclass BoxWeight is used as the upper class to create the Shipping subclass. Shipping inherited all features of BoxWeight and Box and adds a field called cost that contains the cost of Dispatch of such a package.

Multilevel inheritance flowchart:

inheritance in java

Example: how to use Multilevel inheritance in java:

output:

inheritance in java

Because of inheritance, Shipment can use the previously defined classes of Box and BoxWeight, adding only the additional information required by your specific application. This is part of the value of the inheritance; It allows code to be reused. This example illustrates another important point: super () always refers to the constructor in the next upper class (or superclass). The super () in the Shipment method calls the constructor in BoxWeight. The super () in the BoxWeight method calls the constructor in Box. In a class hierarchy, when an upper class Constructor requires parameters, then all subclasses must pass these parameters Line.’ This applies regardless of whether a subclass requires its own parameters or not.


Hierarchical inheritance:

In hierarchical inheritance, a class serves as the upper class (base class) for more than one subclass. In the following figure, class A serves as the base class for derived classes B, C, and D.

Hierarchical inheritance flowchart:

inheritance in java

Example: how to use hierarchical inheritance in java:

output:

inheritance in java



Related Article:

Java Class And Object With Programming Examples

Java Packages In Full Detail With Programming Examples

Java for Loop Statements with Programming Examples

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: