Java中的抽象方法 [英] Abstract methods in Java
问题描述
我想写一个抽象方法,但是编译器一直报错:
I want to write an abstract method but the compiler persistently gives this error:
抽象方法不能有主体
我有一个这样的方法:
public abstract boolean isChanged() {
return smt else...
}
这里出了什么问题?
推荐答案
抽象方法意味着它没有默认实现,一个实现类将提供细节.
Abstract methods means there is no default implementation for it and an implementing class will provide the details.
本质上,你会有
abstract class AbstractObject {
public abstract void method();
}
class ImplementingObject extends AbstractObject {
public void method() {
doSomething();
}
}
因此,正如错误所述:您的抽象方法不能有主体.
So, it's exactly as the error states: your abstract method can not have a body.
Oracle 网站上有完整的教程:http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
您会这样做的原因是多个对象可以共享某些行为,但不是所有行为.
The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.
一个非常简单的例子是形状:
A very simple example would be shapes:
您可以拥有一个通用图形对象,它知道如何重新定位自身,但实现类实际上会绘制自己.
You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.
(这是从我上面链接的网站上截取的)
(This is taken from the site I linked above)
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
这篇关于Java中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!