Java MCQ Output based Questions - Overriding in Java

In this article, we will cover some Java MCQ output based questions which will help extend your Java knowledge. Usually In Interviews nowadays, interviewer are more focused on negative questions rather than conceptual questions, and If you go through below questions, It will surely give you an add on and add value to your experience.

Java MCQ Output based Questions

Overriding in Java

  • What is the output of following program?
    • class Derived 
      {
          protected final void getDetails()
          {
              System.out.println("Derived class");
          }
      }
        
      public class Test extends Derived
      {
          protected final void getDetails()
          {
              System.out.println("Test class");
          }
          public static void main(String[] args)
          {
              Derived obj = new Derived();
              obj.getDetails();
          }
      }
    • a) Derived class
      b) Test class
      c) Runtime error
      d) Compilation error
      • Explanation - Final and static methods cannot be overriden
  • What is the output of following program?
    • class Derived 
      {
          public void getDetails(String temp)
          {
              System.out.println("Derived class " + temp);
          }
      }
        
      public class Test extends Derived
      {
          public int getDetails(String temp)
          {
              System.out.println("Test class " + temp);
              return 0;
          }
          public static void main(String[] args)
          {
              Test obj = new Test();
              obj.getDetails("GFG");
          }
      }
    • a) Derived class GFG
      b) Test class GFG
      c) Compilation error
      d) Runtime error
Explanation - The overriding method must have same signature, which includes, the argument list and the return type

  • What is the output for below program?

class Derived 

  • {

        public void getDetails()

        {

            System.out.println("Derived class");

        }

    }

      

    public class Test extends Derived

    {

        protected void getDetails()

        {

            System.out.println("Test class");

        }

        public static void main(String[] args)

        {

            Derived obj = new Test();  // line xyz

            obj.getDetails();

        }

    }
  • a) Test class

    b) Compilation error due to line xyz

    c) Derived class

    d) Compilation error due to access modifier 
  • Explanation - The overriding method can not have more restrictive access modifier.
// file name: Main.java

class Base {
protected void foo() {}
}
class Derived extends Base {
void foo() {}
}
public class Main {
public static void main(String args[]) {
Derived d = new Derived();
d.foo();
}
}

Output - Compile error

Explanation - foo() is protected in Base and default in Derived. Default access is more restrictive. When a derived class overrides a base class function, more restrictive access can’t be given to the overridden function. If we make foo() public, then the program works fine without any error.

public class Base
{
private int data;

public Base()
{
data = 5;
}

public int getData()
{
return this.data;
}
}

class Derived extends Base
{
private int data;
public Derived()
{
data = 6;
}
private int getData()
{
return data;
}

public static void main(String[] args)
{
Derived myData = new Derived();
System.out.println(myData.getData());
}
}

a) 6

b) 5

c) Compile time error

d) Run time error


Explanation - When overriding a method of superclass, the method declaration in subclass cannot be more restrictive than that declared in the superclass.


What is the output of below program?

import java.io.IOException;

  

class Derived 

{

    public void getDetails() throws IOException //line 23

    {

        System.out.println("Derived class");

    }

}

  

public class Test extends Derived

{

    public void getDetails() throws Exception //line 24

    {

        System.out.println("Test class");

    }

    public static void main(String[] args) throws IOException //line 25

    {

        Derived obj = new Test();

        obj.getDetails();

    }

}


a) Compilation error due to line 23

b) Compilation error due to line 24

c) Compilation error due to line 25

d) All the above

Explanation - The exception thrown by the overriding method should not be new or more broader checked exception. In the code above, Exception is more broader class of checked exception than IOException, so this results in compilation error. 

What is the output of below program?

class Derived 

{

    public void getDetails()

    {

        System.out.printf("Derived class ");

    }

}

  

public class Test extends Derived

{

    public void getDetails()

    {

        System.out.printf("Test class ");

        super.getDetails();

    }

    public static void main(String[] args)

    {

        Derived obj = new Test();

        obj.getDetails();

    }

}


a) Test class Derived class

b) Derived class Test class

c) Compilation error

d) Runtime error

Explanation - super keyword is used to invoke the overridden method from a child class explicitly.

What is the output of below program?

public class Test

{

private static int value = 20;

public int s = 15;

public static int temp = 10;

public static class Nested

{

private void display()

{

System.out.println(temp + s + value);

}

}

public static void main(String args[])

{

Test.Nested inner = new Test.Nested();

inner.display();

}

}


a) Compilation error

b) 1020

c) 101520

d) None of the above


Explanation - A non-static variable can not be accessed in static nested inner class. “Nested” cannot access non-static variables[variable s in this case].


import java.io.*;

public class Test

{

public void display() throws IOException

{

System.out.println("Test");

}


}


class Derived extends Test

{

public void display() throws IOException

{

System.out.println("Derived");

}

public static void main(String[] args) throws IOException

{

Derived object = new Derived();

object.display();

}

}


a) Test

b) Derived

c) Compilation error

d) Runtime error


public class Test extends Thread

{

public static void main(String[] args)

{

String a = "GeeksforGeeks";

String b = new String(a);

int value = 0;

value = (a==b) ? 1:2;

if(value == 1)

{

System.out.println("GeeksforGeeks");

}

else if(value == 2)

{

System.out.println("Geeks for Geeks");

}

else

{

System.out.println("GFG");

}

}

}


a) GeeksforGeeks

b) Geeks for Geeks

c) GFG

d) None of the above

public class Test

{

try

{

public Test()

{

System.out.println("GeeksforGeeks");

throw new Exception();

}

}

catch(Exception e)

{

System.out.println("GFG");

}

public static void main(String[] args)

{

Test test = new Test();

}

}

a) GeeksforGeeks

b) GFG

c) Compilation error

d) None of the above

Explanation -  Constructors cannot be enclosed in try/catch block.


public interface Test

{

public int calculate();

protected interface NestedInterface

{

public void nested();

}

}


a) Compile time error due to NestedInterface

b) Compile time error due to access modifier of NestedInterface

c) No Compile time error

d) NestedInterface cannot hold any function declaration. 


Explanation - Access modifier of NestedInterface can only be public


public class Test

{

private int data = 5;


public int getData()

{

return this.data;

}

public int getData(int value)

{

return (data+1);

}

public int getData(int... value)

{

return (data+2);

}


public static void main(String[] args)

{

Test temp = new Test();

System.out.println(temp.getData(7, 8, 12));

}

}

a) Either Compile time or Runtime error

b) 8

c) 10

d) 7 

(int… values) is passed as parameter to a method when you are not aware of the number of input parameter but know that the type of parameter(in this case it is int). When a new object is made in the main method, variable data is initialized to 5. A call to getData() method with attributes (7, 8 ,12), makes a call to the third getData() method, which increments the value of data variable by 2 and return 7.


public class Base

{

private int multiplier(int data)

{

return data*5;

}

}


class Derived extends Base

{

private static int data;

public Derived()

{

data = 25;

}

public static void main(String[] args)

{

Base temp = new Derived();

System.out.println(temp.multiplier(data));

}

}


a) 125

b) 25

c) Runtime error

d) Compile time error


Explanation - Since the method multiplier is marked as private, it isn’t inherited and therefore is not visible to the Derived.



public class javaclass

{

static

{

System.out.printf("%d", 1);

}

static

{

System.out.printf("%d", 2);

}

static

{

System.out.printf("%d", 3);

}

private static int myMethod()

{

return 4;

}

private int function()

{

return 5;

}


public static void main(String[] args)

{

System.out.printf("%d", (new javaclass()).function() + myMethod());

}

}

a) 123
b) 45
c) 12345
d) 1239

Explanation - static blocks in Java are executed even before the call to main is made by the compiler. In the main method, a new object of javaclass is made and its function() method is called which return 5 and the static method myMethod() returns 4 i.e., 4+5 = 9. Therefore, the output of the program is 1239, because 123 is printed on the console even before main method executes and main method on execution returns 9.

 // filename Main.java

class Test {

protected int x, y;

}


class Main {

public static void main(String args[]) {

Test t = new Test();

System.out.println(t.x + " " + t.y);

}

}

Output - 0 0 
Explanation - In Java, a protected member is accessible in all classes of the same package and in inherited classes of other packages. Since Test and Main are in the same package, no access-related problems in the above program. Also, the default constructors initialize integral variables as 0 in Java

public class Demo{
public static void main(String[] arr){
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = 500;
Integer num4 = 500;
if(num1==num2){
System.out.println("num1 == num2");
}
else{
System.out.println("num1 != num2");
}
if(num3 == num4){
System.out.println("num3 == num4");
}
else{
System.out.println("num3 != num4");
}
}
}

  • a) num1 == num2
        num3 == num4
  • b) num1 == num2
        num3 != num4
  • c) num1 != num2
        num3 == num4
  • d) num1 != num2
        num3 != num4
Explanation - We always thought that whenever two object references are compared using “==”, it always evaluates to “false”. But here Integer caching changes the results.Integer class has a caching range of -128 to 127. Whenever a number is between this range and autoboxing is used, it assigns the same reference. That’s why for value 100, both num1 and num2 will have the same reference, but for the value 500 (not in the range of -128 to 127), num3 and num4 will have different reference.

public class Demo{
public static void main(String[] arr){
}
public static void main(String arr){
}
}

  • a) Nothing
  • b) Error
Explanation -  We can overload main() too. But JVM will always call main() that has String[] argument.

// filename: Test.java

class Test {

// Declaring and initializing integer variable
int x = 10;

// Main driver method
public static void main(String[] args)
{

// Creating an object of class inside main()
Test t = new Test();

// Printing the value inside the object by
// above created object
System.out.println(t.x);
}
}

Output = 10
 

// Main.java

public class Main

{

public static void gfg(String s)

{

System.out.println("String");

}

public static void gfg(Object o)

{

System.out.println("Object");

}


public static void main(String args[])

{

gfg(null);

}

} //end class

Output - String

Explanation -In case of method overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ is a more specific type than ‘java.lang.Object’. In this case the method which takes ‘String’ as a parameter is chosen. 

 // Main.java

public class Main

{

public static void gfg(String s)

{

System.out.println("String");

}

public static void gfg(Object o)

{

System.out.println("Object");

}

public static void gfg(Integer i)

{

System.out.println("Integer");

}


public static void main(String args[])

{

gfg(null);

}

} //end class

Output - Compile time error

Explanation -In this case of method Overloading, the most specific method is chosen at compile time. 

As ‘java.lang.String’ and ‘java.lang.Integer’ is a more specific type than ‘java.lang.Object’,but between ‘java.lang.String’ and ‘java.lang.Integer’ none is more specific. 

In this case the Java is unable to decide which method to call. 


class superClass

{

final public int calc(int a, int b)

{

return 0;

}

}

class subClass extends superClass

{

public int calc(int a, int b)

{

return 1;

}

}

public class Gfg

{

public static void main(String args[])

{

subClass get = new subClass();

System.out.println("x = " + get.calc(0, 1));

}

}


Output - Compile time error

Explanation - The method calc() in class superClass is final and so cannot be overridden.

public class Gfg
{
public static void main(String[] args)
{
Integer a = 128, b = 128;
System.out.println(a == b);

Integer c = 100, d = 100;
System.out.println(c == d);
}
}
Output
false
true

Explanation - In the source code of Integer object we will find a method ‘valueOf’ in which we can see that the range of the Integer object lies from IntegerCache.low(-128) to IntegerCache.high(127). Therefore the numbers above 127 will not give the expected output. 

public class Test
{
private static float temp()
{
public static float sum = 21;
return(--(sum));
}
public static void main(String[] args)
{
Test test = new Test();
System.out.println(test.temp());
}
}

a) 21

b) 20

c) Compilation error

d) Runtime error


Explanation - static variables are associated with the class and are therefore, not allowed inside a method body.


// filename : Test1.java

final interface Test

{

int MAXIMUM = 1500;


void m1();

}


class Test1 implements Test {


@Override public void m1()

{

System.out.println("From Test1 m1 method");

}


public static void main(String[] args)

{

new Test1().m1();

}

}


a) Compilation error

b) Runtime error

c) From Test1 m1 method


Explanation - Interfaces can never be declared final as they are meant to be implemented in derived classes




 

Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD