Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Explain with a code sample how you can prevent a


Download 1.52 Mb.
Pdf ko'rish
bet39/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   35   36   37   38   39   40   41   42   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain with a code sample how you can prevent a
method from being overridden.


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.




Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   35   36   37   38   39   40   41   42   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling