I know that 'final' keyword specified in method definition declare that these method cannot be overridden. But what if I want a method to return a final object? How do you specify this in Java?
class A{
final int x;
A(){
x = 5;
}
final int getx(){
return x;
}
}
class B extends A{
final int x;
B(){
x = 5;
}
final int getx(){
return x;
}
}
class he{
public static void main(String args[]){
A a = new A();
final int x = a.getx();
System.out.println(x);
}
}
The above code gives a compilation error. I know the reason that I am overriding a final method. But my intention was to return a final object from getx() (i.e return x as a final integer).
This is my C++ equivalent code. It works just fine.
#include <bits/stdc++.h>
class A{
public:
const int x;
A():x(5){
}
const int getx(){
return x;
}
};
class B:public A{
public:
const int x;
B():x(5){
}
const int getx(){
return x;
}
};
int main(){
A *a = new A();
const int x = a->getx();
std::cout<<x<<std::endl;
return 0;
}
This is because C++ has a two different keywords - "const" and "final". In C++ 'final' keyword is specified in the end of function prototype, something like this:
virtual int getx() final {}
And so the two keyword distinguishes "what is the return type of a method" and "which methods cannot be overridden".
My question is: Is there a way of doing the same in Java?