More on inheritance

Let's discuss some notorious tricky questions and misconceptions regarding inheritance in Java. 

Let's get started with some of the more well-known questions asked concerning inheritance. Take a look at the following block of code:

class X
{
//Class X members
}

class Y
{
//Class Y members
}

class Z extends X, Y
{
//Class Z members
}

In the preceding code snippet, we have the X and Y class and some data fields or methods inside it. The Z class inherits the X and Y classes. Is this allowed? The answer is no. Java does not allows multiple inheritances, whereas it is allowed in C++. So here, we can conclude that the preceding code snippet is not right and will throw an error.

This is also one of the differences between inheritance and interfaces, as an interface allows us to use multiple interfaces at a time.

Take a look at the following example:

class A
{
int i = 10;
}

class B extends A
{
int i = 20;
}

public class MainClass
{
public static void main(String[] args)
{
A a = new B();
System.out.println(a.i);
}
}

Here, we have an A class and it has an i variable. There is also a B class that extends the A class, and we also have its local i variable set as 20. Now, in MainClass, we create an object for the B class. What does this step actually mean? Here, we are creating an object and saying that this object of this B class should refer to the properties of the A class. Though we have permission to access this B class through this a object, we can only access the properties or methods of the A class, because the B class has permission to access the A class here, as we are extending it.

The question here is what will a.i print—20 or 10? The answer is, it will print the variable value of 10, as A a = new B(); explicitly tells a that it is an object of the B class, but we need to access the methods present in the A class. If we want this output as 20, we change the syntax to B a = new B();

You may get such questions if you attend Java quizzes or a complex interview. These are the important pieces of information that you have to know regarding inheritance, and you can plan accordingly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.132.214