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?
final in Java and const in C++ are very different things and trying to applying ideas from C++ about constants to Java does not work.
In Java, final for datatypes means
Now, if I am returning a value from a function in Java, it is either a native type, which we return by value, or a user defined type, which we return by reference. In both of these cases, the final qualifier on our return value is redundant.
In C++ however, a const qualified return value (let's say a reference to const for simplicity) means that the object underlying the returned reference is immutable, and so you cannot call non const functions using that reference.
final was added in C++11 and means that this member function cannot be overridden by an inheriting class (same as Java).
The takeaway is that Java does not have const correctness that same way that C++ does and your life will be easier if you don't mix these concepts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With