Q) Which is/are false statements
- final class cannot be inherited
- final method can be inherited
- final method can be overridden
- final variable of a class cannot be changed.
Answer: 3
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
- Constructor
- final method
- Both
- None
Answer: 1
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?
- Cannot override private method of a class
- Protected methods are visible to only immediate child class
- Public methods of a class are visible to all.
- All
Answer: 4
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
- final class
- abstract class
- final and abstract both
- none
Answer: 1
If we want to make a class not to be extended, we should mark the class as a final class.