Dil.
Dil.

Reputation: 2076

Does abstract class methods have a body or not?

I had came through a theory that abstract class methods doesn't have a method body, only the method signature. And although a method didn't assigned abstract keyword in a method declaration it automatically convert to an abstract in JVM.
So how come this eat() method has a body and how come it doesn't get to override in Swan class.

public abstract class Animal {

    protected int age;

    public void eat() {
        System.out.println("Animal is eating");
    }

    public abstract String getName();
}

class Swan extends Animal {

    public String getName() {
        return "Swan";
    }
}

Upvotes: 0

Views: 7071

Answers (3)

scottb
scottb

Reputation: 10084

I had came through a theory that abstract class methods doesn't have a method body, only the method signature.

As it happens, both Java classes and methods can be abstract. An abstract method is a method that may only have a signature.

Among other things, an abstract Java class:

  • may contain abstract methods, concrete methods, or both
  • may not be instantiated directly
  • defines a type (just like an interface does)

A concrete Java class:

  • may not contain abstract methods (only concrete methods are allowed)
  • may be directly instantiated
  • can define a type, but interfaces (and sometimes abstract classes) are often better used for this purpose

Upvotes: 1

user207421
user207421

Reputation: 310903

I had came through a theory that abstract class methods doesn't have a method body, only the method signature.

That's not a theory, it is a fact, specified in the JLS #8.4.3.1 'Abstract methods', but it applies to abstract methods, not to all methods in an abstract class.

And although a method didn't assigned abstract keyword in a method declaration it automatically convert to an abstract in JVM.

No it doesn't. Nothing about it in the JLS #8.1.1.1 'Abstract classes'.

So how come this eat() method has a body

Because it isn't abstract.

and how come it doesn't get to override in Swan class.

I don't know what this means.

Upvotes: 1

Anindya Dutta
Anindya Dutta

Reputation: 1982

From the Oracle tutorial:

Abstract Classes Compared to Interfaces

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

If you define a method, then it can be referenced just like any other super class method.

Upvotes: 1

Related Questions