MCQs – Java Inheritance


Q) Which is/are false statements
  1. final class cannot be inherited
  2. final method can be inherited
  3. final method can be overridden
  4. final variable of a class cannot be changed.
View Answer
Answer: C
Final class cannot be inherited.
If a non-final class contains final method then it can be inherited but cannot be overridden in child class.
final variable a of a class cannot be changed and it will be a constant.

 

Q) Which cannot be inherited from a base class in Java programming
  1. Constructor
  2. final method
  3. Both
  4. None
View Answer
Answer: A
Constructor of a class cannot be inherited. But note that they can be invoked from a derived class. final method can be inherited just they cannot be overridden in sub class.

Q) Which cannot be inherited from a base class in Java programming?
  1. Cannot override private method of a class
  2. Protected methods are visible to only immediate child class
  3. Public methods of a class are visible to all.
  4. All
View Answer
Answer: D
Child class cannot access private methods of a base class; hence, they cannot be overridden in child class. Protected methods are visible to only immediate child class.
In below Java code example, compiler will throw an error as in derived class method f2() is calling private method of base class i.e. f1(). If we make it protected or private, then it will work.

class Base {
	
	private void f1(){
	
		System.out.println("f1()");
	}
	
}

class Derived extends Base {
	
	public void f2(){
		
		f1();//not visible here as it is private in base class
		
		System.out.println("f2()");
	}
	
}


public class Program {

	public static void main(String[] args) {

		Derived d = new Derived();
        d.f2();

	}

}


Q) To prevent a class to be inherited / extended, the class should be
  1. final class
  2. abstract class
  3. final and abstract both
  4. none
View Answer
Answer: A
If we want to make a class not to be extended, we should mark the class as a final class.



Leave a Comment