What is Inheritance in Java? – Day 12

Published by Maneet Srivastav on

Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, one can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it.

In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the members defined by the superclass and adds its own, unique elements.

Basic of Inheritance

To inherit a class, we simply incorporate the definition of one class into another by using the extends keyword. To see how, let’s begin with a short example.  The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.

//a supercalss
class A {
int i,j;
void showIJ() {
System.out.println(“Value of i and j : “,i+” “+j)00;
}
}

//subclass extending class A
class B extends A {
int k;
void showK() {
System.out.println(“Value of k : “+k);
}

void sum() {
System.out.println(“i+j+k : “+i+j+k);
}
}

class Inheritance() {
public static void main(String args[]) {
A ob1 = new A();
B ob2 = new B();

//SuperClass may be used by itself
ob1.i = 10;
ob1.j = 30;
System.out.println(“Contents of SuperClass Object :”);
ob1.showIJ();

//SubClass has access to all public members of it’s SuperClass
ob2.i = 20;
ob2.j = 60;
ob2.k = 5;
System.out.println(“Contents of SubClass Object :”);
ob2.showIJ();
ob2.showK();

System.out.println(“Sum : “);
ob2.sum();
}
}

Even though A is a superclass for B, it is also a completely independent, stand-alone class. Being a superclass for a subclass does not mean that the superclass cannot be used by itself. Further, a subclass can be a superclass for another subclass.

Creating a Multilevel Hierarchy

Up to this point, we have been using simple class hierarchies that consist of only a superclass and a subclass. However, you can build hierarchies that contain as many layers of inheritance as you like. As mentioned, it is perfectly acceptable to use a subclass as a superclass of another. For example, given three classes called 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 of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.

In a class hierarchy, if a superclass constructor requires arguments, then all subclasses must pass those arguments “up the line.” This is true whether or not a subclass needs arguments of its own.

When Constructors Are Executed

When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy executed? For example, given a subclass called B and a superclass called A, is A’s constructor executed before B’s, or vice versa? The answer is that in a class hierarchy, constructors complete their execution in order of derivation, from superclass to subclass. Further, since super( ) must be the first statement executed in a subclass’ constructor, this order is the same whether or not super( ) is used. If super( ) is not used, then the default or parameterless constructor of each superclass will be executed.

Using Abstract Classes

Sometimes we want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. The definition of method( ) is simply a placeholder. It will not compute and display any type of object.

This approach can be useful in certain situations—such as debugging—it is not usually appropriate. We may have methods that must be overridden by the subclass in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java’s solution to this problem is the abstract method.

We require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);

No method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, we cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be declared abstract itself.

Use of super

There will be times when one wants to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private).  In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super.
super has two general forms. The first calls the superclass’ constructor. The second is used to access a member of the superclass that has been hidden by a
member of a subclass.

  • Using super to Call Superclass Constructors : A subclass can call a constructor defined by its superclass by use of the following form of super: super(arg_list); Here, arg_list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass constructor.
  • A Second Use for super : The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member. Here, a member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.

Using final with Inheritance

The keyword final has three uses. First, it can be used to create the equivalent of a named constant. The other two uses of final apply to inheritance. Both are examined here.

  • Using final to Prevent Overriding : While method overriding is one of Java’s most powerful features, there will be times when we want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.
  • Using final to Prevent Inheritance : Sometimes we want to prevent a class from being inherited. To do this, precede the class declaration with the final. Declaring a class as final implicitly declares all of its methods as final, too. As it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

The Object Class

There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array.
Object defines the following methods, which means that they are available in every object.

  • Object clone( ) : Creates a new object that is the same as the object being cloned.
  • boolean equals(Object object) : Determines whether one object is equal to another.
  • void finialize( ) : Claeed before an unused object is rejected.
  • Class<type> getClass( ) : Obtains the class of an object at run time.
  • int hashCode( ) : Returns the hash code associated with invoking object.
  • void notify( ) / notifyAll( ) : Resumes execution of a thread waiting on the invoking object.
  • String toString( ) : Returns a string that describes the object.
  • void wait( Parameter ) : Waits on another thread of execution.

 

CONNECT WITH THE AUTHOR ON LINKEDIN.

YOU CAN VISIT OUR WEBSITE BRIGHTERBEES FOR INFORMATION ABOUT JAVA.
TO GET ON THE BLOG OF DAY 7 OF THIS JAVA SERIES click here.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY CONNECT WITH US