Java – Multiple Choice Questions and Answers – Inheritance & Polymorphism

HOME



 class Apple {
       public void print() { System.out.println("Apple"); }
   }
   class Banana extends Apple {
       public void print() { System.out.println("Banana"); }
   }
   public class Test {
       public static void main(String[] args) {
           Apple  apple = new Banana();
           apple.print();
       }
   }



 class Apple {
       public void print() { System.out.println("Apple"); }
   }
   class Banana extends Apple {
       public void print() { System.out.println("Banana"); }
   }
   public class Test {
       public static void main(String[] args) {
           Apple  apple = new Apple();
           apple.print();
       }
   }

class A {
    A(int x) { }
}

class B extends A {
    B(int x) {
        System.out.println("Constructor B");
    }
}

public class Test {
    public static void main(String[] args) {
        B obj = new B(10);
    }
}

class Parent {
    void method() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
}

public class Test {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.method();
    }
}






  class Parent {
    public void print() {
        System.out.println("Parent");
    }
}

class Child extends Parent {
    public void print() {
        System.out.println("Child");
        super.print();
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.print();
    }
}

package pack1;
public class A {
    public void display() {
        System.out.println("Hello from A");
    }
}

package pack2;
import pack1.A;
public class B {
    public static void main(String args[]) {
        A obj = new A();
        obj.display();
    }
}


class A 
    {
        int i;
        void display() 
        {
            System.out.println(i);
        }
    }    

    class B extends A 
    {
        int j;
        void display() 
        {
            System.out.println(j);
        }
    }    
    
   class Test
    {
        public static void main(String args[])
        {
            B obj = new B();
            obj.i=1;
            obj.j=2;   
            obj.display();     
        }
   }

 class A 
    {
        int i;
    }    

    class B extends A 
    {
        int j;
        void display() 
        {
            super.i = j + 1;
            System.out.println(j + " " + i);
        }
    }    

    class Test 
    {
        public static void main(String args[])
        {
            B obj = new B();
            obj.i=1;
            obj.j=2;   
            obj.display();     
        }
   }





public class Parent {
    void m1(String x) {
        System.out.println("One");
    }
}

public class Derived extends Parent{
    public void m1(String x) {
        System.out.println("Two");
        super.m1(null);
    }
}

public class Test {
    public static void main(String[] args){
        Parent obj = new Derived();
        obj.m1(null);
    }
}

public class Test{

    void m1(String x){
        System.out.println("One");
    }
    
    protected void m1(String x, String y){
        System.out.println("Two");
    }
    
    public static void main(String[] args){
        Test obj = new Test();
        obj.m1("ABC");
        obj.m1("PQR", "XYZ");
    }
}

public class PolymorphismDemoClass {
    void add(int x, int y){
        System.out.println("1. Addition is: " +(x+y));
    }
    
   void add(int y, int x){
        System.out.println("2. Addition is: " +(x+y));
    }
    
   public static void main(String[] args){
        PolymorphismDemoClass obj = new PolymorphismDemoClass();
        obj.add(20, 30);
    }
}


Java Tutorials

Java is a general-purpose programming language that is a concurrent, class-based, and object-oriented language. Java follows the concept of “write once and run anywhere (WORA).” This means that compiled Java code can be run on all different platforms that support Java. There’s no need for recompilation.

Eclipse IDE

Chapter 1 How to Download and Install Eclipse IDE
Chapter 2 How to Clone a project from GitLab using Eclipse
Chapter 3 How to Export Eclipse projects to GitLab

IntelliJ IDE

Chapter 1 How to install IntelliJ on Windows
Chapter 2 How to create a Java project in IntelliJ
Chapter 3 How to Clone a project from GitLab using IntelliJ
Chapter 4 How to Export IntelliJ project to GitLab

Basics of Java

Chapter 1 How to Download & Install Java JDK 11 in Windows
Chapter 2 Data Types and Operators in Java
Chapter 3 Decision Making in Java – If, If Else, Switch, Break, Continue
Chapter 4 Loop Control Statements in Java – For, While, Do While, Enhanched For Loop
Chapter 5 String Manipulation
Chapter 6 Difference between == and equals() method in Java
Chapter 7 Arrays in Java
Chapter 8 Java Access Modifiers: Explained with Examples
Chapter 9 ArrayList in Java
Chapter 10 How to compare ArrayLists – contains?
Chapter 11 How to compare ArrayLists – containsAll method?
Chapter 12 Methods in Java
Chapter 13 Method Overloading in Java
Chapter 14 Constructors in Java   
Chapter 15 This Keyword in Java   
Chapter 16 Static Keyword – Static Variable and Static Method in Java
Chapter 17 Difference between Static Method and Non-Static Method
Chapter 18 How to use Java Lambda expression to create thread via Runnable function
Chapter 19 runAsync and supplyAsync in ComputableFuture in Java8
Chapter 20 HashMap in Java
Chapter 21 LinkedHashMap in Java
Chapter 22 Iterators in Java

OOPs Concepts

Chapter 1 Class and Object in Java
Chapter 2 Inheritance in Java
Chapter 3 Encapsulation in Java
Chapter 4 Polymorphism in Java
Chapter 5 Abstraction in Java
Chapter 6 Interface in Java
Chapter 7 Difference between Abstract Class and Interface

Exceptions in Java

Chapter 1 Exception Handling in Java
Chapter 2 Java Exceptions Tutorial: Built-in and User-defined Exceptions
Chapter 3 Flow control in try catch finally in Java
Chapter 4 Multiple Catch Exceptions
Chapter 5 Throw in Java
Chapter 6 Throws in Java

Data Handling (Excel Manipulation)

Chapter 1 How to download and install Apache POI
Chapter 2 Reading Excel Data with Apache POI in Java
Chapter 3 How to Write Data to Excel File in Java using Apache POI
Chapter 4 How to update existing excel in Java
Chapter 5 Java Excel Tutorial: Creating Excel with Formulas Using Apache POI
Chapter 6 Change Font Style in Excel with Apache POI – NEW

Multiple Choice Questions

Chapter 1 Multiple questions on Exception Handling in Java

Java Library

Chapter 1 AssertJ – Fluent Assertions in Java

Inheritance in Java

HOME

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another class.

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).

Inheritance is applicable for public and protected members only. Private members can’t be inherited.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

The keyword used for inheritance is extends

Syntax

class derived-class extends base class
{
//methods and variables
}

Below is an example of Inheritance. In the below example, ParentCalculation is the Base class (parent class) and has a method addition. ChildCaclculation is the derived class (child class) which has extends base class ParentCalculation. When an object of ChildCaclculation class is created, a copy of all methods and fields of the superclass acquire memory in this object. That is why by using the object of the subclass we can also access the members of a superclass. 

Base Class

public class ParentCalculation {

	int z;

	public void addition(int x, int y) {
		z = x + y;
		System.out.println("The sum of the given numbers:" + z);
	}

}

Derived Class

public class ChildCaclculation extends ParentCalculation {

	int c;

	public void multiplication(int a, int b) {
		c = a * b;
		System.out.println("The multiplication of the given numbers:" + c);
	}

	public static void main(String[] args) {
		ChildCaclculation cal = new ChildCaclculation();
		cal.addition(10, 14);
		cal.multiplication(5, 6);

	}

}

Output

The sum of the given numbers:24
The multiplication of the given numbers:30

Types of Inheritance in Java

Below are the different types of inheritance available in Java. 

1. Single Inheritance

In single inheritance, subclass (derived) inherit the features of superclass (base). In the image below, class A serves as a base class for the derived class B.

Base Class

public class Employee {

	String name = "Tom";
	int emp_no = 12001;

	public void displayEmployee() {
		System.out.println("Base Class");

		System.out.println("Name :" + name);
		System.out.println("Emp_No :" + emp_no);
	}
}

Derived Class

package JavaDemo.Inheritance;

public class Department extends Employee {

	String deptName = "IT Division";

	public void displayDept() {
		System.out.println("Derived Class");

		System.out.println("Department Name :" + deptName);
	}

	public static void main(String[] args) {

		Department dept = new Department();

		// Derived method
		dept.displayDept();

		// Base Method
		dept.displayEmployee();

	}

}

Output

Derived Class
Department Name :IT Division
Base Class
Name :Tom
Emp_No :12001

2. Multilevel Inheritance

In this, derived class extends an base class as well as the derived class act as a base class for another derived class. In the below example, Employee is Base class, Department is intermediate derived class and SubDivision is derived class.

Base Class

package JavaDemo.Inheritance;

public class Employee {

	String name = "Tom";
	int emp_no = 12001;

	public void displayEmployee() {
		System.out.println("Base Class");

		System.out.println("Name :" + name);
		System.out.println("Emp_No :" + emp_no);
	}
}

Intermediate Derived Class

package JavaDemo.Inheritance;

public class Department extends Employee {

	String deptName = "IT Division";

	public void displayDept() {
		System.out.println("Intermediate Derived Class");

		System.out.println("Department Name :" + deptName);
	}

	public static void main(String[] args) {

		Department dept = new Department();

		// Intermediate Derived method
		dept.displayDept();

		// Base Method
		dept.displayEmployee();

	}

}

Derived Class

package JavaDemo.Inheritance;

public class SubDivision extends Department {

	String sub_division = "Production Support";

	public void displaySubDivision() {
		System.out.println("Derived Class");

		System.out.println("SubDivision Name :" + sub_division);
	}

	public static void main(String[] args) {

		SubDivision div = new SubDivision();

		// Derived method
		div.displaySubDivision();

		// Intermediate Derived method
		div.displayDept();

		// Base Method
		div.displayEmployee();

	}

}

Output

Derived Class
SubDivision Name :Production Support
Intermediate Derived Class
Department Name :IT Division
Base Class
Name :Tom
Emp_No :12001

3.  Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclasses.

In the below example, Employee is the base class. Department and Salary are the derived classes.

Base Class

package JavaDemo.Inheritance;

public class Employee {

	String name = "Tom";
	int emp_no = 12001;

	public void displayEmployee() {
		System.out.println("Base Class");

		System.out.println("Name :" + name);
		System.out.println("Emp_No :" + emp_no);
	}
}

Derived Class1

public class Department extends Employee {

	String deptName = "IT Division";

	public void displayDept() {
		System.out.println("Derived Class 1");

		System.out.println("Department Name :" + deptName);
	}

	public static void main(String[] args) {

		Department dept = new Department();

		// Derived method
		dept.displayDept();

		// Base Method
		dept.displayEmployee();

	}

}

Derived Class2

package JavaDemo.Inheritance;

public class Salary extends Employee {

	float Salary = 65000;

	public void displaySalary() {
		System.out.println("Derived Class 2");
		System.out.println("Salary :" + Salary);
	}

	public static void main(String[] args) {

		Salary sal = new Salary();
		sal.displaySalary();
		sal.displayEmployee();

		System.out.println("=========================");

		Department dept = new Department();
		dept.displayDept();
		dept.displayEmployee();

	}

}

Output

Derived Class 2
Salary :65000.0
Base Class
Name :Tom
Emp_No :12001
=========================
Derived Class 1
Department Name :IT Division
Base Class
Name :Tom
Emp_No :12001

4. Multiple Inheritance

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. We can achieve multiple inheritances only through Interfaces.

5. Hybrid Inheritance

 It is a combination of single and multiple inheritance. As Java doesn’t support multiple inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.