【发布时间】:2017-06-05 06:08:18
【问题描述】:
我知道方法定义中指定的“final”关键字声明这些方法不能被覆盖。但是如果我想要一个方法返回一个最终对象呢?你如何在 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++ 中,'final' 关键字在函数原型的末尾指定,如下所示:
virtual int getx() final {}
所以这两个关键字区分“什么是方法的返回类型”和“哪些方法不能被覆盖”。
我的问题是:有没有办法在 Java 中做同样的事情?
【问题讨论】:
-
@juanchopanza 哦,是的。对此感到抱歉。让我编辑
-
不清楚你所说的“在 Java 中做同样的事情”是什么意思
-
与您的问题无关,但您应该阅读Why should I not #include <bits/stdc++.h>?
-
@juanchopanza 有没有办法从java中的方法返回final int?就像我们在 C++ 中返回 const int 一样。
-
@Someprogrammerdude 竞争性编程迫使我使用这些技巧 :)
标签: java