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 1 of 2.

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!

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?

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.

Zaki said:   7 years ago
Method can't be overridden here as because it's a final but in super class, the value we are giving are not initialized that the reason we get compile time error. And class method treated as its own.

Hushen Beg said:   7 years ago
The final class can't be extended.
The final method can't override in subclass.
The final method can be overload.
The final variable values can't changed.

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.

Hemant said:   8 years ago
Final method cannot be overridden.

Correct me if I am wrong, but we can rewrite the method.

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


Post your comments here:

Your comments will be displayed after verification.