Implementation for abstract method

Q

qazmlp

A pure virtual function can have implementation in C++.
Can an abstract method have implementation in Java?
 
C

Carl Howells

qazmlp said:
A pure virtual function can have implementation in C++.
Can an abstract method have implementation in Java?

No. If it could, it wouldn't be an *abstract* method. It would be a
concrete method, that can be overridden. That is, non-final.

If you want to make sure that a class is subclassed before it's
instantiated, mark the class as abstract, rather than its methods, if
you want a default implementation for each method.
 
T

TT \(Tom Tempelaere\)

Carl Howells said:
No. If it could, it wouldn't be an *abstract* method. It would be a
concrete method, that can be overridden. That is, non-final.

Is there an equivalent? Forcing to override, yet giving an implementation?

Tom.
 
T

Tor Iver Wilhelmsen

A pure virtual function can have implementation in C++.

Er, isn't a pure virtual C++ function defined as

virtual returntype name(arguments) = 0;

Where do you put the code?
 
Q

qazmlp

Tor Iver Wilhelmsen said:
Er, isn't a pure virtual C++ function defined as

virtual returntype name(arguments) = 0;

Where do you put the code?
The above declaration will be part of inside class declaration.
The definition should be given outside that.
It looks like this:
class test
{
virtual returntype name(arguments) = 0;
};
returntype test::name(arguments)
{
}
 
D

Dale King

Tor Iver Wilhelmsen said:
Er, isn't a pure virtual C++ function defined as

virtual returntype name(arguments) = 0;

Where do you put the code?

I was all set to tell the OP that he was nuts and that a pure virtual method
cannot have a body in C++ by definition, but I did some checking and he is
correct. You can define an implementation for a pure virtual function.

http://www.gotw.ca/gotw/031.htm gives the three primary reasons why:

1. For pure virtual destructors (the main reason)
2. Force conscious acceptance of default behavior
3. Way to force error when calling pure virtual method from constructor.

To the OP's second question, no an abstract method cannot have a body. As to
why, I would say that #1 and #3 in the above list do not apply to Java as it
has no destructors and the semantics are different for calling methods in
the constructor so it won't work for #3. #2 is not important enough to
complicate the language for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top