MCQs – Java Inheritance

Q) Which inheritance in java programming is not supported
  1. Multiple inheritance using classes
  2. Multiple inheritance using interfaces
  3. Multilevel inheritance
  4. Single inheritance

Answer: 1

NOTE: Java does not support multiple inheritance of classes but it supports multiple inheritance for interfaces. Means, a class cannot inherit more than one class but it can inherit and implement multiple interfaces.


Q) What is subclass in java?
  1. A subclass is a class that extends another class
  2. A subclass is a class declared inside a class
  3. Both above.
  4. None of the above.

Answer: 1
A subclass is a class that extends another class. In other words, subclass inherits the functionality of the class it extends. See below example.

class BaseClass {
	
	public void foo() {
		System.out.println("Base class");
	}
}

//This is a subclass that inherit 
//public methods of base class
class SubClass extends BaseClass {
	
}

public class Program {

	public static void main(String[] args) {

		SubClass s = new SubClass();
        	s.foo();
	}
}

Output:
Base class


Q) If class B is subclassed from class A then which is the correct syntax
  1. class B:A{}
  2. class B extends A{}
  3. class B extends class A{}
  4. class B implements A{}

Answer: 2

Below is the example.

class A{
}

//Class B is sub classed from class A
class B extends A{

}

Q) Order of execution of constructors in Java Inheritance is
  1. Base to derived class
  2. Derived to base class
  3. Random order
  4. none

Answer: 1
On object creation of derived class, first base class constructor and then derived class constructor will be called.
Below is the java code example

class Animal{
	
	public Animal(){
		System.out.println("Base Constructor");
	}
}


class Cat extends Animal{

	public Cat(){	
		System.out.println("Derived Constructor");		
	}
}
public class Program {

	public static void main(String[] args) {

		Cat c = new Cat();   

	}

}

Output

Base Constructor
Derived Constructor


Related Posts