Java中的抽象方法 [英] Abstract methods in Java

查看:99
本文介绍了Java中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个抽象方法,但编译器会持续发出此错误:

I want to write an abstract method but the compiler persistently gives this error:


抽象方法不能有正文

abstract methods cannot have a body

我有这样的方法:

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网站的完整教程: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆