Inheritance in Java

One of the Java’s strongest feature is Inheritance. As the name suggest, it is about  inheriting something from someone. Java class inherits members of another class with the help of this inheritance feature.

As a formal definition inheritance can be said as a feature that allows one class to inherit the members of another class.

Consider the code given below: create two separate class

super class Book and subclass LanguageBook and helper class DemoBook

class Book {

	double price;
	int publicationYear;
	String name;
	String authorName;
	
	public Book(){
		
	}
	
	
	public double calculateDiscountPrice(){
		double discountedPrice = price - price*10/100;
		return discountedPrice;
	}

}

class LanguageBook extends Book {

	String dvdName;

	public LanguageBook(double price, int publicationYear, String name,
	    String authorName, String dvdName) {
		// by default the default constructor of super class gets called

		// first four variables are inherited from super class Book
		this.price = price;
		this.publicationYear = publicationYear;
		this.name = name;
		this.authorName = authorName;

		// sub class's own variable
		this.dvdName = dvdName;

	}


	public static void main(String[] args) {

		

LanguageBook langBook = new LanguageBook(400, 2009,
				"French Language Basics", "Frank Giroud", "Listen and Learn");

		}

}

public class DemoBook {

	public static void main(String[] args) {

		LanguageBook langBook = new LanguageBook(400, 2009,
				"French Language Basics", "Frank Giroud", "Listen and Learn");

		// we call the calculateDiscountPrice method of superclass with subclass
		// object langBook
		System.out.println("Book Name : " + langBook.name + " , DVD Name : "
				+ langBook.dvdName + " And Price is "
				+ langBook.calculateDiscountPrice());

	}

}
Try It

Output of above program will be

Book Name : French Language Basics , DVD Name : Listen and Learn And Price is 360.0

The Book class is straightforward. It has four instance variable, a default constructor and a method calculating price after giving 10% discount.

Pay attention to the LanguageBook class. At the first line it is written:

public class LanguageBook extends Book

extends is a keyword in Java. By this we are declaring that this LanguageBook class will be a subclass of Book. The book class in this case will be called the super class.

When declaring a sub class super class relation using extends, couple of things happens in back ground. LanguageBook is inheriting the members of Book class.

The instance variables of Book now has become the instance variable of LanguageBook. So LanguageBook can use the variables as its own, it has now 5 instance variables (one of its own plus four inherited from the Book class).

Check the code inside the constructor of LanguageBook.  As you know the constructor instantiate a class. So before the instantiation of sub class, java first calls the super class constructor (internally).

Check the comment section inside LanguageBook constructor. // by default the default constructor of super class gets called.

That’s why we have added a blank constructor in the Book class. That constructor has no job. But if you remove that, you will get a compilation error.

Now DemoBook class main method has this code:

System.out.println("Book Name : " + langBook.name + " , DVD Name : "
				+ langBook.dvdName + " And Price is "
				+ langBook.calculateDiscountPrice());

Look how langBook object is using the variable ‘name’ as one of its own (dvdName). Also pay attention to langBook.calculateDiscountPrice() method call.

The LanguageBook class does not have any method with this name, but the Book class have. Java is smart enough to call the method defined in the super class.

This is a very regular feature used in java. Super class used to have a generic method, and every subclass of it use this method without declaring it again in its own class.

Remember though that the inheritance is one directional. The sub class will inherit the members from super class. The super class has no knowledge what the sub class has added to it.

Consider the code below:

Change the Book class to this:

Book book = langBook;
System.out.println("Book name " + book.name);
System.out.println(book.dvdName);

First line does not create any problem as ‘name’ is defined in Book class. But the second line will give you a compilation error. The Book class does not have any knowledge of the variable ‘dvdName’. The ‘dvdName’ is added by its sub class LanguageBook, so it is only known to LanguageBook class.

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. ... It depends on your definition of "inherit"

Inheritance chain

You might be wondering whether one class can inherit members of more than one class. This possible through inheritance chain.

Suppose classA extends classB. And classB extends class C. By inheritance chain class A now inherits the members of both classB and classC. This makes perfect sense.

This chain has no limit in a theoretical sense. That means in the above example classC can extends classD, that may extends classE and so on. But if you design your code in this way, in future you yourself will get confuse. So better to keep the chain length short.

Multiple Inheritance

Now you may want to extend your power of inheritance and think, I want to build a class that will inherit members from multiple class. Here java will stop you to do so. This feature is called as multiple inheritance. Java does not allow multiple inheritance. Like if you write a code as shown below, you will get a compilation error.

Class Subclass extends classA, classB

Multiple Inheritance through Interfaces

Multiple Inheritance allows a class to have more than one super class and to inherit features from all parent class. it is achieved using interface.

create two interfaces Base1 and Base2 and a class SubClass which implements Base1 and Base2 and MainHelper class to call the methods of class SubClass

interface Base1{
 int e1 = 10;
 public void mul();
}
interface Base2{
 int e2 = 15;
public void add();
}
class SubClass implements Base1, Base2 {
public void mul() {
System.out.println("mul result is "+(e1*e2));
}
public void add() {
System.out.println("add result is "+(e1+e2));
}
}

public class MainHelper 
{
    public static void main(String[] args) 
    {
        SubClass sc = new SubClass();
        sc.mul();
        sc.add();
    }
}
Try It

Output

mul result is 150
add result is 25

"Super" Keyword in Java

We have a super class called Book and subclass called LanguageBook and Helper class called DemoBook

class Book {

	double price;
	int publicationYear;
	String name;
	String authorName;

	public Book() {

	}

	public Book(double price, int publicationYear, String name,
			String authorName) {
		this.price = price;
		this.publicationYear = publicationYear;
		this.name = name;
		this.authorName = authorName;
	}

	public double calculateDiscountPrice() {
		double discountedPrice = price - price * 10 / 100;
		return discountedPrice;
	}

}

class LanguageBook extends Book {

	// subclass variable
	String dvdName;

	public LanguageBook(double price, int publicationYear, String name,
			String authorName, String dvdName) {
		// calling the super class constructor
		super(price, publicationYear, name, authorName);

		// sub class's own variable
		this.dvdName = dvdName;

	}

}

public class DemoBook {

	public static void main(String[] args) {

		LanguageBook langBook1 = new LanguageBook(400, 2009,
				"French Language Basics", "Frank Giroud", "Listen and Read");

		System.out.println("Book Information : Name : " + langBook1.name +    " , DVD Name : "
				+ langBook1.dvdName + " And Price is "
				+ langBook1.calculateDiscountPrice());

	}

}
Try It


Output:

Book Information : Name : French Language Basics , DVD Name : Listen and Read And Price is 360.0

 

Pay attention to the LanguageBook class.

It has two constructor. The first one we have seen earlier, except one line

// calling the super class constructor

super(price, publicationYear, name, authorName);

super is a keyword in Java. As the comment section describes, this is a standard way to call super class constructor.

The LanguageBook class inherited price, publicationYear, name, and authorName variable from its super class Book. It makes sense to let the initialization of these variables to be done by Book class itself.

With super we are calling the constructor of Book class with the required parameter. We do not have to do the initialization of these variable in LanguageBook class as we did the last time.

One important thing to remember about super, it must be the first statement inside the constructor. Otherwise compiler will give you a compilation error. You can guess the reason why compiler wants the super class constructor to be called in the first line.

The super class initialization must be done before sub class.

public LanguageBook(LanguageBook clone)
{
		// calling the super class constructor
		super(clone.price, clone.publicationYear, clone.name, clone.authorName);

		// sub class's own variable
		this.dvdName = clone.dvdName;
}

Using ‘super’ to access the members of super class

Apart from calling super class constructor, super has another functionality, which is accessing the super class member.

Remember, member is both variable and method.

Consider the code below:

class Test {

	int abc;

}


class SubTest extends Test {

	int abc;
	int xyz;

	public SubTest(int m, int n) {
		super.abc = m; // abc in super class Test
		abc = m + n; // abc in this class 
		xyz = n;
	}

	public void show() {
		System.out.println("The variable in SubTest class is " + abc + " and "
				+ xyz + " The variables in Test is " + super.abc);
	}
}


public class DemoTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		SubTest subTest = new SubTest(10, 20);

		subTest.show();

	}

}
Try It

Run the code, you will get an output as:
The variable in SubTest class is 30 and 20 The variables in Test is 10

As you can see, super.abc is referring the abc variable in the super class Test.


Next > < Prev
Scroll to Top