问题描述
我想编写一个抽象方法,但编译器会持续发出此错误:
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.
基本上,你会有
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网站的完整教程:
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中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!