Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract methods in Java

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

abstract methods cannot have a body

I have a method like this:

public abstract boolean isChanged() {     return smt else... } 

What is wrong here?

like image 954
caner Avatar asked May 16 '11 16:05

caner


People also ask

Why abstract method is used in Java?

In any programming language, abstraction means hiding the irrelevant details from the user to focus only on the essential details to increase efficiency thereby reducing complexity. In Java, abstraction is achieved using abstract classes and methods.

What is abstract method and its use?

An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

What is called abstract method?

Abstract methods are those types of methods that don't require implementation for its declaration. These methods don't have a body which means no implementation. A few properties of an abstract method are: An abstract method in Java is declared through the keyword “abstract”.

What is abstract in Java with example?

Abstraction in Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message.


1 Answers

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

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.

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() {         ...     } } 
like image 50
Reverend Gonzo Avatar answered Sep 24 '22 03:09

Reverend Gonzo