这是C ++代码
public class First {
public:
virtual int firstmethod(int a, int b) = 0;
virtual int secondmethod(int a, int b, int c) = 0;
}
public class Second : public First {
public:
int firstmethod(int a, int b) {
int result = a * b;
return result + 3;
}
}
到目前为止,这是我对Java的支持
public class First {
static in firstmethod(int a, int b) = 0;
static int secondmethod(int a, int b, int c) = 0;
}
public class Second extends First
{
static int firstmethod(int a, int b)
{
int result = a * b;
return result + 3;
}
}
这是对的吗? 编辑 我编辑了这个问题,使其更加清晰,更容易理解
答案 0 :(得分:3)
不,一点也不。静态方法永远不是虚拟的,Java对纯虚方法不使用“= 0”(它使用“abstract”关键字。)具有抽象方法的类本身必须标记为抽象。默认情况下,Java方法也不公开 - 每个方法必须单独标记为“public”。
答案 1 :(得分:3)
这将是:
public class Whatever {
public int mymethod(int one, int two) { return 0; }
public int myothermethod(int one, int two, int three) { return 0; }
}
public class However extends Whatever
{
@Override // optional annotation
public int mymethod(int one, int two)
{
int answer = one * two;
return answer + 3;
}
}
但是你可以实现Whatever
。为了防止对Whatever的实现,要么将其标记为abstract
,要么将其interface
标记出来。这完全取决于您希望类继承Whatever
的方式。由于不能有多重继承,请明智地选择。
public interface Whatever {
public int mymethod(int one, int two);
public int myothermethod(int one, int two, int three);
}
public class However implements Whatever
{
public int mymethod(int one, int two)
{
int answer = one * two;
return answer + 3;
}
public int myothermethod(int one, int two, int three) {
return 0;
}
}
或
public abstract class Whatever {
public abstract int mymethod(int one, int two);
public abstract int myothermethod(int one, int two, int three);
}
public class However extends Whatever
{
public int mymethod(int one, int two)
{
int answer = one * two;
return answer + 3;
}
public int myothermethod(int one, int two, int three) {
return 0;
}
}
** 编辑 **
在评论的一些启示之后,你的C ++到Java等价物实际上是你在C ++代码上使用virtual
类方法的第三个构造。
答案 2 :(得分:1)
我想说你正在寻找的java翻译:
public interface Whatever {
public static int myMethod(int one, int two);
public static int myOtherMethod(int one, int two, int three);
}
public class However implements Whatever {
public static int myMethod(int one, int two) {
int answer = one * two;
return answer + 3;
}
public static int myOtherMethod(int one, int two, int three) {
int answer = one * two;
return answer + 3;
}
}
另外,为了清晰和惯例,我会谨慎地将变量命名为“一个”或“两个”,因为这可能会导致混淆。
答案 3 :(得分:1)
这是我的翻译:
public abstract class Whatever {
public abstract int mymethod(int one, int two);
public abstract int myothermethod(int one, int two, int three);
}
public class However extends Whatever {
@Override
public int mymethod(int one, int two) {
int answer = one * two;
return answer + 3;
}
@Override
public int myothermethod(int one, int two, int three) {
return ...;
}
}
我也喜欢Yanick关于使用接口的答案;这是一个更好的方法。我正在保留我的答案,因为使用@Override
,这对Java代码很有用。