我知道在方法定义中指定的'final'关键字声明这些方法不能被覆盖。但是如果我想要一个方法返回最终对象呢?你如何在Java中指定它?Java v/s C++ - 从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);
}
}
上面的代码给出了一个编译错误。我知道我压倒最后一种方法的原因。但我的意图是从getx()返回一个最终对象(即返回x作为最终整数)。
这是我的C++等效代码。它工作得很好。
#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;
}
这是因为C++有两个不同的关键字 - “const”和“final”。在函数原型,像这样的结尾指定C++“最终”关键字:
virtual int getx() final {}
所以这两个关键字的区别“什么是方法的返回类型”和“该方法不能被重写” 。
我的问题是:有没有办法在Java中做同样的事情?
@juanchopanza哦,是的。对不起。让我编辑 – Sushant
不清楚你的意思是“在Java中做同样的事” – juanchopanza
与你的问题无关,但你应该阅读[为什么我不应该#include?](http:/ /stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) –