Unit-4
Inheritance, Packages and Exception Handling using Java
Q1) What is inheritance in java?
A1) Inheritance in Java is a mechanism in which one object acquires all the properties and behaviours of a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
Terms used in Inheritance
The syntax of Java Inheritance
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.
Q2) Write an example of java inheritance
A2) Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
Q3) Explain types of inheritance in java
A3) Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
Output:
meowing...
eating...
Q4) Why multiple inheritances are not supported in java?
A4) To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.
Compile Time Error
Q5) Explain Super class references, Using super
A5) Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe two classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of Calculation class.
Copy and paste the following program in a file with name My_Calculation.java
Example
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Compile and execute the above code as shown below.
javac My_Calculation.java
java My_Calculation
After executing the program, it will produce the following result −
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of the contents of the superclass is made within it. That is why, using the object of the subclass you can access the members of a superclass.
The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But using the superclass reference variable ( cal in this case) you cannot call the method multiplication(), which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note− A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Q6) Explain super keyword with example
A6) The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.
super.variable
super.method();
Sample Code
This section provides you a program that demonstrates the usage of the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass.
Copy and paste the program in a file with name Sub_class.java.
Example
class Super_class {
int num = 20;
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
sub.display();
// Invoking the display() method of superclass
super.display();
// printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);
// printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+ super.num);
}
public static void main(String args[]) {
Sub_classobj = new Sub_class();
obj.my_method();
}
}
Compile and execute the above code using the following syntax.
javacSuper_Demo
java Super
On executing the program, you will get the following result −
Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Q7) Explain invoking superclass constructor
A7) Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.
super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to invoke the parametrized constructor of the superclass. This program contains a superclass and a subclass, where the superclass contains a parameterized constructor which accepts a integer value, and we used the super keyword to invoke the parameterized constructor of the superclass.
Copy and paste the following program in a file with the name Subclass.java
Example
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String args[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
On executing the program, you will get the following result −
Output
The value of the variable named age in super class is: 24
Q8) What is IS-A Relationship in java?
A8) IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.
public class Animal {
}
public class Mammal extends Animal {
}
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}
Now, based on the above example, in Object-Oriented terms, the following are true −
Now, if we consider the IS-A relationship, we can say −
With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example
class Animal {
}
class Mammal extends Animal {
}
class Reptile extends Animal {
}
public class Dog extends Mammal {
public static void main(String args[]) {
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This will produce the following result −
Output
true
true
true
Since we have a good understanding of the extends keyword, let us look into how the implements keyword is used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface. Interfaces can never be extended by a class.
Example
public interface Animal {
}
public class Mammal implements Animal {
}
public class Dog extends Mammal {
}
The instanceof Keyword
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal.
Example
interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal {
public static void main(String args[]) {
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This will produce the following result −
Output
true
true
true
Q9) What is HAS-A relationship in java?
A9) HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets look into an example −
Example
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle {
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.
Types of Inheritance
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore following is illegal −
Example
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance.
Q10) Explain Constructor call sequence in java
A10) A static block is a block of code with a static keyword. In general, these are used to initialize the static members of a class. JVM executes static blocks before the main method at the time loading a class.
Example
publicclassMyClass{
static{
System.out.println("Hello this is a static block");
}
publicstaticvoidmain(String args[]){
System.out.println("This is main method");
}
}
Output
Hello this is a static block
This is main method
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
publicclassMyClass{
MyClass(){
System.out.println("Hello this is a constructor");
}
publicstaticvoidmain(String args[]){
newMyClass();
}
}
Output
Hello this is a constructor
Instance method
These are the normal methods of a class (non static), you need to invoke them using an object of the class −
Example
publicclassMyClass{
publicvoiddemo(){
System.out.println("Hello this is an instance method");
}
publicstaticvoidmain(String args[]){
newMyClass().demo();
}
}
Output
Hello this is an instance method
Order of execution
When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.
ExamplepublicclassExampleClass{
static{
System.out.println("Hello this is a static block");
}
ExampleClass(){
System.out.println("Hello this a constructor");
}
publicstaticvoiddemo(){
System.out.println("Hello this is an instance method");
}
publicstaticvoidmain(String args[]){
newExampleClass().demo();
}
}
Output
Hello this is a static block
Hello this a constructor
Hello this is an instance method