Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 1)
1.
What will be the output of the program?
class A 
{
    final public int GetResult(int a, int b) { return 0; } 
} 
class B extends A 
{ 
    public int GetResult(int a, int b) {return 1; } 
} 
public class Test 
{
    public static void main(String args[]) 
    { 
        B b = new B(); 
        System.out.println("x = " + b.GetResult(0, 1));  
    } 
}
x = 0
x = 1
Compilation fails.
An exception is thrown at runtime.
Answer: Option
Explanation:

The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden.

Discussion:
18 comments Page 2 of 2.

Chiranjeevi said:   10 years ago
Yes GetResult.... is final we cannot override that method in child class.
If variable final we cannot change value.
If class is final we cannot create child class.
If method is final we cannot override that method.

Abhi said:   10 years ago
Yes it is giving compile time error but how and why?

I know Final methods does not get inherited. In that case GetResult () in class B should be treated as its own method not as it is trying to override any method.

Anyone with clarification?

Harish said:   1 decade ago
Final methods can't be overridden.

Pranay soundharya said:   1 decade ago
Final methods cannot be overridden. Here overridden means same method and same signature in different subclass and superclass.

Coolbuddy said:   1 decade ago
Ya it's true that if we use final then method can't be override. But in this question. Object should call it's own method.

Vishal said:   1 decade ago
final methods cannot be overridden.
final variables cannot be modified.
final class cannot be instantiated.

Bhavya said:   1 decade ago
Yes it is correct because class a is final so, it can't overridden. Thank you.

Sundar said:   1 decade ago
Compilation Result:

----------------------------------------
C:\Java>javac Test.java

Test.java:7: GetResult(int,int) in B cannot override GetResult(int,int) in A; overridden method is final.

----------------------------------------

Hope this will help you. Have a nice day!


Post your comments here:

Your comments will be displayed after verification.