Question

Must all abstract methods in java be declared with void return type? i.e.

public abstract void myMethod();

instead of

public abstract myMethod();

What happens when the method is not declared with void return type?

I suppose that a method declaration as below is also wrong due to the existence of the 'scope' symbols.

public abstract void myMethod() {}

Kindly clarify my doubts, as I am still a beginner in this area.

Was it helpful?

Solution

Must all abstract methods in java be declared with void return type?

No. You can give any return type.

What happens when the method is not declared with void return type?

You must give a return type to a method. A method declared without any return type won't compile. A method signature comprises of - method name, return type, list of formal parameters if any, list of type parameters if any. You can't skip the first two.

I suppose that a method declaration as below is also wrong due to the existence of the 'scope' symbols.

I guess you meant, "curly braces". Yes that would fail to compile. abstract methods can't have body.

OTHER TIPS

What happens when the method is not declared with void return type?

In Java, You should declare what a method returns in it's signature. It can be void or some other object type or primitive type. It doesn't matter whether it's a abstract method or normal method.

Must all abstract methods in java be declared with void return type?

No, They can declared to return any object type, primitive type and, also declared to return void to indicate it return nothing.

I suppose that a method declaration as below is also wrong due to the existence of the 'scope' symbols.

public abstract void myMethod() {}

Yes, it's wrong. An abstract method can't have method body. It's a compilation error.

No. You can put your own return type in the method declarations of abstract classes

Whether a method is abstract or not has no bearing on a methods return type.

An abstractmethod can have either a void or non-void return type:

public absract int getValue();
public absract void doSomething();

Abstract only determines that the current method/class will be defined by some future subclass.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top