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() {
...
}
}
Answer from Reverend Gonzo on Stack OverflowAbstract methods in Java - Stack Overflow
implementing abstract methods/classes in java - Stack Overflow
java - What are abstract classes and abstract methods? - Stack Overflow
Use of abstract methods and interfaces?
Videos
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() {
...
}
}
If you use the java keyword abstract you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.
In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.
If I understand your question correctly, Yes.
public abstract class TopClass {
public abstract void methodA();
public abstract void methodB();
}
public abstract class ClassA extends TopClass {
@Override
public void methodA() {
// Implementation
}
}
public class ClassB extends ClassA {
@Override
public void methodB() {
// Implementation
}
}
In this example, ClassB will compile. It will use it's own implementation of methodB(), and ClassA's implementation of methodA(). You could also override methodA() in ClassB if desired.
You could have two abstract classes, X and Y, where Y extends X. In that case it could make sense for Y to implement an abstract method of X, while still being abstract. Another non-abstract class Z could extend Y. However, in your example, for A to implement its own abstract methods is a contradiction, the point of making them abstract is so it doesn't provide implementations, it just specifies what the method signatures should look like.
- Abstract class is one which can't be instantiated, i.e. its object cannot be created.
- Abstract method are method's declaration without its definition.
- A Non-abstract class can only have Non-abstract methods.
- An Abstract class can have both the Non-abstract as well as Abstract methods.
- If the Class has an Abstract method then the class must also be Abstract.
- An Abstract method must be implemented by the very first Non-Abstract sub-class.
- Abstract class in Design patterns are used to encapsulate the behaviors that keeps changing.
An abstract class is a class that can't be instantiated. It's only purpose is for other classes to extend.
Abstract methods are methods in the abstract class (have to be declared abstract) which means the extending concrete class must override them as they have no body.
The main purpose of an abstract class is if you have common code to use in sub classes but the abstract class should not have instances of its own.
You can read more about it here: Abstract Methods and Classes
I understand the point of abstract classes even from a semantic perspective.
But I don't understand why would I need to use abstract methods? My issue is that they:
Don't have a body so it's not like they're helping avoid copy-paste code.
They *have* to be implemented by the first concrete class, and that feels like an obligation that takes away some sort of flexibility from the programmer.
Why not use empty methods in their place?
I have a similar gripe about interfaces.
How are they helping implement polymorphism if the methods don't have a body that I can reuse? If I have 2 classes with the same interface (say Pet interface, since I'm using Head First Java as a resource and that's the example they use) and that interface has a method actFriendly(). And now if both my concrete classes implement that same Pet interface in the exact same manner, I have to type the same code in both my classes, aka copy paste stuff and somehow that just feels like a big programming no-no.
Something about these two tools is just not clicking for me...I'd appreciate any help!
Thanks in advance!
One of the most obvious uses of abstract methods is letting the abstract class call them from an implementation of other methods.
Here is an example:
class AbstractToy {
protected abstract String getName();
protected abstract String getSize();
public String getDescription() {
return "This is a really "+getSize()+" "+getName();
}
}
class ToyBear extends AbstractToy {
protected override String getName() { return "bear"; }
protected override String getSize() { return "big"; }
}
class ToyPenguin extends AbstractToy {
protected override String getName() { return "penguin"; }
protected override String getSize() { return "tiny"; }
}
Note how AbstractToy's implementation of getDescription is able to call getName and getSize, even though the definitions are in the subclasses. This is an instance of a well-known design pattern called Template Method.
The abstract method definition in a base type is a contract that guarantees that every concrete implementation of that type will have an implementation of that method.
Without it, the compiler wouldn't allow you to call that method on a reference of the base-type, because it couldn't guarantee that such a method will always be there.
So if you have
MyBaseClass x = getAnInstance();
x.doTheThing();
and MyBaseClass doesn't have a doTheThing method, then the compiler will tell you that it can't let you do that. By adding an abstract doTheThing method you guarantee that every concrete implementation that getAnInstance() can return has an implementation, which is good enough for the compiler, so it'll let you call that method.
Basically a more fundamental truth, that needs to be groked first is this:
You will have instances where the type of the variable is more general than the type of the value it holds. In simple cases you can just make the variable be the specific type:
MyDerivedClassA a = new MyDerivcedClassA();
In that case you could obviously call any method of MyDerivedClassA and wouldn't need any abstract methods in the base class.
But sometimes you want to do a thing with any MyBaseClass instance and you don't know what specific type it is:
public void doTheThingsForAll(Collection<? extends MyBaseClass> baseClassReferences) {
for (MyBaseClass myBaseReference : baseClassReferences) {
myBaseReference.doTheThing();
}
}
If your MyBaseClass didn't have the doTheThing abstract method, then the compiler wouldn't let you do that.
The deal with abstract classes is that they are abstract, you can define abstract methods and also concrete methods. Them being classes means that when creating new classes you are limited to extending only one per class.
Interfaces on the other hand define abstract methods and also concrete methods through what I now learned is another use of the default keyword (the one I knew was switch cases). Interfaces can also be functional interfaces which means support for lambdas. You can implement more than one interface in a class.
Now that we know that both abstract classes and interfaces provide both support for concrete and abstract methods, and that you can "subclass" more interfaces in one class as opposed to "subclassing" abstract classes, as well as lambdas support for interfaces, why would there be a use for abstract classes? It seems interfaces can do all that abstract classes can do but better.
Basically you want, if possible, to use interfaces wherever possible. The only difference between an interface and an abstract class, aside from classes only being able to extend one class, is that abstract classes can contain state. If you don't need to contain state it's better to use interfaces since a class can implement any number of interfaces.
So to answer your question:
It seems interfaces can do all that abstract classes can do but better.
No. Abstract classes can contain state, interfaces can't.
An example for using interfaces, abstract classes and concrete classes:
public interface UserDb {
void storeUser(User user);
default void storeUsers(User... users) {
for(User u : users) {
storeUser(u);
}
}
}
public abtract class AbstractUserDb implements UserDb {
protected List<User> users = new ArrayList<>();
@Override
public void storeUser(User u) {
users.add(u);
}
}
public class JsonUserDb extends AbstractUserDb {
@Override
public void storeUser(User u) {
super.storeUser(u);
new ObjectMapper().writeValue(users, "users.json");
}
}
Abstract classes can provide implementation of methods as well as just declarations, so they can provide common or base implementations for methods that may be used by many subclasses. Take a look at java.util.AbstractList, for example, which provides some base functionality to make it easier to implement the java.util.List interface. If you want to implement List, you don't have to actually implement all of the methods declared by that interface yourself—you can just extend AbstractList and implement the get() method, and the default implementations of all the other methods provided by AbstractList will work out of the box, using your get() method, to give you a minimal implementation of List.
An abstract method is a method without a body. So you can't just call an abstract method of an abstract class (you cannot instantiate an abstract class directly). If you want to have your abstract game class with the abstract methods you need to have a class that extends this game class and specifically implements these methods without the abstract keyword.
Or you remove the abstract keyword from init and render and then the subclass of your Game class doesn't have to implement these methods but will take the one defined in your Game class.
Alternatively you can remove the abstract keyword from the methods in your game class but still @Override them in your subclass. That way you can define a default behavior for init and render and still change it in a subclass if needed.
public abstract class Game {
public Game() {};
public void init()
{
// do init stuff
}
public void render()
{
// do render stuff
}
}
public class specificGame extends Game {
public specificGame() {};
// no need to implement init and render. But you can still override them
@Override
public void init()
{
// spefic init stuff
}
@Override
public void render()
{
// specific render stuff
}
}
More about abstract classes and methods https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Is this what you want?
This is the main file:
package devex;
import devex.SubClass;
public class MainClass
{
public static void main(String[] args)
{
SubClass.init();
AClass.init();
}
}
The this is the abstract class defining a default init
package devex;
public abstract class AClass
{
public static void init()
{
System.out.println("AClass init");
}
}
This subclass extends AClass and overwrites init
package devex;
public class SubClass extends AClass
{
public static void init()
{
System.out.println("Subclass init");
}
}
The fact that your methods are abstract is secondary, here -- the main issue is that you're calling the methods as if they were declared static:
Game.init()
Game.render()
Instead, what you need in order to call these methods is an instance of the Game class and invoke those methods on that object:
Game game = new SubclassOfGame();
game.init()
game.render()