100.
Answer:
You can prevent a method from being overridden using the final
keyword. The final keyword needs to
be specified in the method
declaration. The following code demonstrates this:
public class Base {
public final void doSomething() {
System.out.println(“Doing something in Base”);
}
}
Here, the class Base has a doSomething method that is marked
as final. So, it cannot be overridden in the sub–class
Suppose we create a sub–class as follows:
public class Sub extends Base{
public void doSomething() { //Line 3
System.out.println(“Doing something in Sub”);
//Line 4
} //Line 5
}
Here, the sub–class Sub overrides
the doSomething method
from Base. Since doSomething is final,
this will result in a
compilation error at Lines 3–5.
The code below has an error. Identify it and state how it
can be fixed.
public class Base {
public void doSomething() { //Line 1
System.out.println(“Doing something in Base”);
}
}
public class Sub extends Base{
private void doSomething() { //Line 2
System.out.println(“Doing something in Sub”);
}
}
Answer:
Here, the base class Base has
a doSomething method that is
marked as public. The sub–class Sub overrides the
doSomething method. However, it is marked as private in the
sub–class at Line 2. So, Line 2 causes a compilation error. This is
because, you cannot reduce the
visibility of an overridden
method. In order to fix the error,
you need to mark the
doSomething method at Line 2 as public.