Return to site

☕🎓JAVA CERTIFICATION QUESTION: final class inheritance

· java

Given:

final class Foo {
    void m() {
	    System.out.println("Foo");
	}
}

final class Bar extends Foo {
    void m() {
	    System.out.println("Bar");
	}
}

public class Test {
    public static void main(String[] args){
	    Foo foo = new Bar();
		foo.m();
	}
}

What happens when compiling and executing the given program?

* It prints 'Foo' to the console

* It prints 'Bar' to the console

* The Foo class fails to compile

* The Bar class fails to compile

* The Test class fails to compile

#java #certificationquestion #ocp

Answer:

the Foo class is declared as final; thus; it cannot be inherited by any other class.

In the given program, class Bar attempts to extend class Foo, hence a compile-time error occurs.