The Best Technical Blog Ever

twitterrss

Inheritance in Java

In this tutorial we will discuss about the feature of java programming called inheritance. The term inheritance itself implies that one class can inherit the properties and behaviours of another class. It gives the idea of reusability, that means a code once written can be used again and again in a number of new classes. If the code can be reused, they can save time and effort in developing and testing a new project.


Inheritance lets you to create classes that are derived from other classes in order to create more complex relationships. The class that does the inheriting is called a child class (derived class or subclass) of the class from which it inherits. Similarly, the class that is inherited is the parent class(base class or superclass).


Suppose if you need to create numerous classes to explain types that aren't identical but have many features in common, for that you can create a base class that defines all the general features. Now from that base class, you can create child classes that inherit the common features. Because child class can use all the features of its base class. It can also add extra features by defining its own methods and fields. It also gives you the chance to change the behaviors of the base class to better suit your needs.


inheritance


This diagram shows a parent-child relationship between a class and its child class. It is also known as IS-A relationship. Note that a line with an arrow is used to describe generalization.


In Java, all classes by default extend the java.lang.Object class. That means, each class in Java is implicitly a subclass of the Object class. A class can extend another class by using the extends keyword. In order to define a class B as a subclass of a class A, it should be written as follows:


Syntax:
class A		  // Parent class
{
    	// fields and methods;
}
class B extends A 	// child class
{
   	// fields and methods;
}


Member Access and Inheritance:

A child class in turn can be extended, unless you specifically make it inextensible by declaring it final. Within a child class you can access its parent class's public and protected methods and fields. If the child class and the parent class are in the same package, you can also access the parent class's default methods and fields. But you cannot access any inherited private data members and member functions directly from the subclass.


Example :
inheritance


In this program the line class InheritanceDemo extends Area tells the compiler that InheritanceDemo is a new class and class Area is inherited in class InheritanceDemo. This makes class Area as the parent of class InheritanceDemo, where class Area and InheritanceDemo are also known as the base class and derived class, respectively. Thus, InheritanceDemo inherits states and behaviours of objects of Area class such as length and width. Apart from deriving from Base class, InheritanceDemo can have its own data members such as height and member functions representing states and behaviours of objects.


Example :
inheritance


All of us know, to access a private data member of a class we have to define a public member function. In the above example, the Name class has one private data member 'name'. To access this string name in the derived class, a public member function printName() is given in base class Name which returns the value of name. In display() method, the private data member 'name' is obtained by the printName() method call, and lastname is concatenated with it to display the output.


Types of inheritance in java:

There are three types of inheritance in java. They are,

  1. single inheritance
  2. multilevel inheritance
  3. hierarchical inheritance

Single-level inheritance:-

A child class inherits from its parent class. So it has one base and one derived class.


inheritance


Multilevel inheritance:-

A class can be derived from another class that is derived from another class (i.e. a class inherits from its parent, this parent in turn inherits from its parent) and so on.


Example :
inheritance


Hierarchical inheritance:-

one class can be a parent of many other classes. Here class A is the base class for two classes: B and C. They can share all fields, methods of class A except private members.


inheritance


Example :
inheritance


Unfortunately, to reduce the complexity, Java does not support the multiple inheritances through classes. Consider a scenario where class C inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. It will lead to compile time error. To achieve multiple and hybrid inheritance, we have to use interface concept. We will learn about interfaces later.


In general, subclass inherits all the members from its base class. But constructors are not considered as members. As a result, a subclass does not inherit constructors from its base class. Again it is possible to override a method by declaring a new member with the same signature in the subclass. For more information, see Method overriding.


We can also declare a abstract method in class, but that method must be overridden in any class that extends the class with this abstract method. It is also possible to declare a class as abstract. So that we cannot create an object from it. As a result, we must extend it in subclass.


Calling base class constructor:

This section explains how the constructors are called when they are present both in super and sub classes, and how the values are passed from sub class to super class. To understand this concept, consider a example of single inheritance in which class A is inherited by class B. Both the classes have their default constructors.


In this case, if we create an object of class B, it automatically calls the constructor of class B, but at the same time, class A is the parent of class B, so constructor of class A will be called first, followed by that of class B. This is so because when derived class has inherited base class, obviously it will be using the data member from base class. Now without calling the constructor of base class, data members of base class will not be initialized and if derived class uses the uninitialized data members of base class, unexpected result may occurs. Calling a constructor of base class first allows base class to properly initialize its data members so that they can be used by derived classes. If super( ) is not used, then the default constructor of each super class will be executed.


When you instantiate a child class by invoking one of its constructors, first the constructor calls the default constructor of the direct parent class. In the parent class, the constructor also calls the constructor of its direct parent class. This process repeats itself until the constructor of the java.lang.Object class is reached.


Example :
inheritance


But in case of parameterized constructors, all of us know that it needs to be called manually by our program. So that, If a super class has a parameterized constructor, then it is the duty of the child class constructor to call the super class's constructor first before executing any other Java statements inside its constructor, otherwise it will create a compile time error. If you are using the super keyword then it must be the first statement inside the constructor of the derived class.


To call super class constructor, child class constructor will use super() method along with the necessary argument values. But, remember that any other member functions apart from constructor cannot call super class's constructor. It is obvious that super class's object will be constructed first before child class's object construction.


Example :
inheritance


In the above program, when statement ColourSub s = new ColourSub("red", "pink"); executes, object s calls the parameterized constructor of ColourSub class and passes parameters red and pink. But, before entering into the body of constructor, here super(s) calls the constructor of ColourBase class and passes s as argument. When control returns, it enters into the body of the constructor. For more details visit constructor.


Calling base class data member with super:

Assume we have a data member whose name is same in base class and child class. Now, the child class can access the base class data member by using the super keyword.


 super.i; // assume i appears both in base class and child class
 

Using final with Inheritance:

1. Prevents Inheritance:

You can prevent your class from extending by making it final using the keyword final in the class declaration. A final class has the property that it cannot be inherited. Declaring a class as final implicitly declares all of its methods as final, too. Since there is no way to override them. When you say that the class is final, you state that there is no need to make any changes, or for safety or security reasons, you do not want sub-classing.


One example of final class is System class defined in package java.lang. Since the designer of the class did not want us to change the behavior of the System class.


Example :
final class Tutorial{
	int a=5;
	String str="java";
	void show()
	{
	
	}
} 

2. Prevents Overriding:

Although method overriding is one of Java's most exciting features, there will be times when you will want to prevent it from occurring. To avoid a method from being overridden, use the final keyword at the start of its declaration. Methods declared as final cannot be overridden. If you try to do so, a compile time error will result.


Example :
final void display()
{
	System.out.println("java tutorial");
}

Inheritance and Casting:

You can only cast an instance of a subclass to its parent class. When a child class extends a parent class, then an instance of the child class is of type child, but also of type parent. However, the reverse is not true! An instance of the parent class is certainly of type parent, but it is not of type child. The cast includes a runtime check, in order for the compiler to safely assume that the cast is used appropriately and is correct. If not, a runtime exception will be thrown.


1. Upcasting:

Casting an object to a parent class is called upcasting. In simple words, when Parent class reference variable refers to Child class object, it is known as Upcasting.


For example, if an instance of Cow is created, it can be upcast to Mammal since the object doesn't stop from being a Cow. It's still a Cow, but it's just treated (labeled) as Mammal and it's Cow properties are hidden until it's downcasted to a Cow again. This is allowed, because Cow is a Mammal. Note that, even though they(Dog & Cow) are both Mammals, Cow cannot be cast to a Dog.


Example :
Cow cow = new Cow();

Mammal obj1 = cow;  //upcasting
Mammal obj2 = new Dog();
obj1.eat();
obj2.sleep();
// The following statements are incorrect.
 // Cow c1 = new Mammal();
 // Dog c2 = new Mammal();
 

Note that the Parent reference variable cannot access the members that are only available in Child. Upcasting can never fail.


inheritance


2. Downcasting:

When the base class type is type cast into a derived class type, it is called a downcast. That means you can try to convert the object of base class type into the type of one of the derived classes (going down). The downcast has to be made explicit.


Cow cow = new Cow();

Mammal obj1 = cow;  //upcasting
Cow c = (Cow)obj1; //downcasting
 

Downcasting to a subclass is only allowed if the parent class reference is already pointing to an instance of the subclass. Otherwise it will generate a compile time error.


Mammal obj1=new Mammal();//not points to an instance of the subclass
Cow c = (Cow)obj1;  // illegal downcasting, compile time error
  

However if you have a group of different Animals and want to downcast them all to a Cow, in that case there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing Runtime Exception (a java.lang.ClassCastException).


Instanceof operator:

The instanceof operator can be used to determine whether an object can be cast to a specific class. It can be used to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. This operator returns true if the left side object can be cast into the right side type without causing an exception. It is normally used in an if statement and its syntax is.


if (objectReference instanceof type) 

where objectReference references an object being inspected.


Cow cow = new Cow();
if(cow instanceof Animal) {
	Animal obj = (Animal) cow;
  	obj.eat();
}
obj.eat(); 

However, applying instanceof on a null reference variable returns false. For example, the following if statement returns false.


 String str = null;
if (str instanceof java.lang.String)

Keypoints to remember in java

1. Java is a high level, robust, secured , platform independent and object oriented programming.... more info

Back to Basics:- Java Syntax

In this session, you are going to refresh some basic set of rules(java syntax), defining how a ... more info

Total Visits
Traffic feed status