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);
    }
}


Polymorphism in Java

HOME

In this tutorial, I’ll explain about Polymorphism in Java. It is one of the four concepts of OOPs. It is a concept where we can perform a single action in multiple ways. Poly means many and morphs means form. Polymorphism allows us to define one interface and have multiple implementations. An example of polymorphism is that there are different forms of communication like calls, SMS, picture messages, etc.

There are 2 types of polymorphism:-

  1. Method Overloading in Java – This is an example of compile time (or static polymorphism)
  2. Method Overriding in Java – This is an example of runtime time (or dynamic polymorphism)

Complie Time Polymorphism

It is also known as static polymorphism. Method Overloading is an example of static polymorphism. It is a feature that allows a class to have more than one method having the same name if their argument lists are different. Error if any occur, resolved during compile time.

Below is an example of static polymorphism.

public class Calculation {

	void sum(int a, int b) {
		System.out.println("Sum of 2 numbers :" + (a + b));
	}

	void sum(int x, int y, int z) {
		System.out.println("Sum of 3 numbers :" + (x + y + z));
	}

}
public class PolymorphismTest {

	public static void main(String[] args) {

		Calculation cal = new Calculation();
		cal.sum(10, 5);
		cal.sum(2, 6, 4);

	}
}

The output of the above program is

Dynamic Polymorphism

It is also known as Dynamic Method Dispatch. In this, the call to the overridden method happens at the runtime. This type of polymorphism is achieved by Method Overriding. Declaring a method in sub class that is already present in the parent class is known as method overriding. 

Below is an example of dynamic polymorphism

Parent Class

public class Bank {

	 //Overridden method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of parent class");
		System.out.println("Interest Rate of Bank :" + 0);

	}
}

Child 1 Class

public class BOI extends Bank {

    // Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 1 class");
		System.out.println("Interest Rate of BOI Bank :" + 4.1);

	}

}

Child 2 Class

public class BoFA extends Bank {

    // Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 2 class");
		System.out.println("Interest Rate of BofA Bank :" + 3.2);

	}

}

Child 3 Class

public class SBI extends Bank {

	// Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 3 class");
		System.out.println("Interest Rate of SBI Bank :" + 5.3);

	}
}

Test Class

public class StaticPolTest {

	public static void main(String[] args) {

		Bank bank1 = new Bank();
		bank1.getRateOfInterest();

		BOI bank2 = new BOI();
		bank2.getRateOfInterest();

		BofA bank3 = new BofA();
		bank3.getRateOfInterest();

		SBI bank4 = new SBI();
		bank4.getRateOfInterest();
	}

}

The output of the above program is

Points to note for Method Overriding:-

  1. The argument list of the overriding method (method of subclass) must match the overridden method (the method of parent class). The data types of the arguments and their sequence should exactly match.
  2. The access Modifier of the overriding method (method of a subclass) cannot be more restrictive than the overridden method of the parent class. 

Suppose, I have changed the access modifier of SBI class from public to protected and then run the StaticPolTest program. In that case, I’ll get a compile-time error.

getRateOfInterest() method of parent class
Interest Rate of Bank :0
getRateOfInterest() method of child 1 class
Interest Rate of BOI Bank :4.1
getRateOfInterest() method of child 2 class
Interest Rate of BofA Bank :3.2
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from Bank

	at JavaDemo.Polymorphism.SBI.getRateOfInterest(SBI.java:6)
	at JavaDemo.Polymorphism.StaticPolTest.main(StaticPolTest.java:17)

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