abstract class versus interface

R

Rajarshi Guha

Hi,
I've been brushing up on Java and had a question regarding use of
abstract class and interfaces.

As I understand an abstract class is only useful if I want to use it as a
superclass since it cannot be instantiated. However I also see that an
interface also essentially serves the same purpose in that it cannot be
instantiated and is generally used as a superclass in hierarchies.

So what *is* the difference between these two constructs? And why would
I prefer one over the other?

Thanks,
 
M

Matt Humphrey

Rajarshi Guha said:
Hi,
I've been brushing up on Java and had a question regarding use of
abstract class and interfaces.

As I understand an abstract class is only useful if I want to use it as a
superclass since it cannot be instantiated. However I also see that an
interface also essentially serves the same purpose in that it cannot be
instantiated and is generally used as a superclass in hierarchies.

So what *is* the difference between these two constructs? And why would
I prefer one over the other?

An abstract class can have method implementations and instance variables
that will be common to all classes. Also, don't forget that an interface
can also be instantiated (in a manner of speaking) on the fly via an
anonymous class, as in:

Runnable r = new Runnable () {
public void run () {
// Do run stuff here
}};

Cheers,
Matt Humphrey (e-mail address removed) http://www.iviz.com/
 
T

Tony Morris

Also, don't forget that an interface
can also be instantiated (in a manner of speaking) on the fly via an
anonymous class, as in:

Runnable r = new Runnable () {
public void run () {
// Do run stuff here
}};

No it can't - an interface can never be instantiated.
This is an anonymous inner class that implements the Runnable interface.
In contrast, this is similar to a named inner class that implements the
Runnable interface, which has nothing to do with "instantiating an
interface". The interface itself was never instantiated.

Anonymous inner classes are not restricted to being used with interfaces.
--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
T

Tony Morris

Rajarshi Guha said:
Hi,
I've been brushing up on Java and had a question regarding use of
abstract class and interfaces.

As I understand an abstract class is only useful if I want to use it as a
superclass since it cannot be instantiated. However I also see that an
interface also essentially serves the same purpose in that it cannot be
instantiated and is generally used as a superclass in hierarchies.

So what *is* the difference between these two constructs? And why would
I prefer one over the other?

Thanks,


--

Generally, an interface defines no implementation, an abstract class
provides partial implementation, and a concrete* class provides complete
implementation. Or another way of thinking about it is that interfaces
provide 0% implementation, abstract classes between 0 and 100% (inclusive)
implementation and concrete classes 100% implementation.

Therefore, interfaces provide no method implementations (all abstract), an
abstract class can provide some method implementations, and some not
(abstract), and a concrete class provides all method implementations. A
common strategy of using all three is to provide a common interface, which
serves as the super type, and abstract class that provides method
implementations that will be common to most subtypes, and concrete classes
that inherit from the abstract class to provide complete implementation.

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
N

Niels Dybdahl

So what *is* the difference between these two constructs? And why would
I prefer one over the other?

As mentioned abstract classes can contain method implementations and
instance variables.
On the other hand a class can implement more than one interface but it can
only extend one abstract class.

Niels Dybdahl
 
D

Dale King

Tony Morris said:
Also, don't forget that an interface

No it can't - an interface can never be instantiated.
This is an anonymous inner class that implements the Runnable interface.
In contrast, this is similar to a named inner class that implements the
Runnable interface, which has nothing to do with "instantiating an
interface". The interface itself was never instantiated.

Anonymous inner classes are not restricted to being used with interfaces.


I think you missed the phrase "(in a manner of speaking)".

But I'm not sure I see Matt's point because you can do the same thing with
an abstract class.
 
M

Matt Humphrey

Dale King said:
interfaces.


I think you missed the phrase "(in a manner of speaking)".

But I'm not sure I see Matt's point because you can do the same thing with
an abstract class.

Actually, I was unaware at the time that anonymous classes could subclass
other classes at all--I had only ever seen and used them with interfaces.
My point was only that it is not necessary to have a named class in order to
get an object that implements a particular interface.

Thanks for the civility,
Matt Humphrey (e-mail address removed) http://www.iviz.com/
 
R

Rick Osborn

I know 100 hiring managers are going to
hate me. But this is a POPULAR tech screen question.
Possibly where you heard it from. I did.

An abstract class is more for design patterns and frameworks.

An interface, more loosely defined underlying components. Or if you
won't
know the underlying implementation/implementor. (i.e. the Math
interface
to OS)

Also, as we all know, an object can only inherit ONE class
at a time, and a plethora of interfaces. (i.e. extending Thread vs.
implementing Runnable)


There's more options, but that's just a few.
 
T

Tony Morris

I think you missed the phrase "(in a manner of speaking)".

No I didn't miss the phrase. I was clarifying what was obviously a
misunderstanding.

Consider the following:

// This does NOT instantiate an interface
// Case A
class X implements I
{
void m()
{
I i = new X();
}
}

// And neither does this
// Case B
I i = new I()
{
void m()
{

}
};

The fact that there is a named class (called X) in case A (which I assume
the original "misunderstander" agrees that this is not "instantiating an
interface") and an anonymous class for case B is completely irrelevant to
the fact (instantiaing an interface).
This fact is clearly stated in the Java 2 Language Specification and is also
thoroughly examined in the Sun Certified Programmer for the Java 2 Platform
examination.

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
T

Tony Morris

But I'm not sure I see Matt's point because you can do the same thing with
an abstract class.

You can define an anonymous class of any legal supertype (abstract class,
non-abstract class, interface, etc.)


--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
D

Dale King

Tony Morris said:
No I didn't miss the phrase. I was clarifying what was obviously a
misunderstanding.

You are correcting what was an acknowledged over simplification.
The fact that there is a named class (called X) in case A (which I assume
the original "misunderstander" agrees that this is not "instantiating an
interface") and an anonymous class for case B is completely irrelevant to
the fact (instantiaing an interface).
This fact is clearly stated in the Java 2 Language Specification and is also
thoroughly examined in the Sun Certified Programmer for the Java 2 Platform
examination.


Maybe you have some different meaning to "in a manner of speaking" than I
do. To me that is a disclaimer to say that what it is modifying is not
strictly true, but can loosely be thought of it being so. It is rather
pointless to point out that what was said was not technically true since
that was already understood since the author already acknowledged that by
the phrase "in a manner of speaking".

We are not in disagreement about the technical facts here.
 
T

Tony Morris

Maybe you have some different meaning to "in a manner of speaking" than I
do. To me that is a disclaimer to say that what it is modifying is not
strictly true, but can loosely be thought of it being so.

The only reason I pointed it out is because I interpreted it exactly as you
did, however, it is still incorrect.
That is, "This is not strictly true, but can loosely be thought of it being
so" is incorrect, because it can't even be "loosely thought of as being so".

My example regarding anonymous classes and named classes highlights this
fact. There is no relationship to "subclassing an interface" and the given
example in any way, shape or form. The Java 2 Language Specification also
makes this clear.

The "named class" example that I gave was to point out, and hopefully,
obtain concurrence from the original poster, that the example has nothing to
do with "subclassing an interface". I then went on to point out that the
fact that an anonymous class is used (as opposed to a named class) is just
as relevant (that is, no relevance).

Anonymous class is to subclassing an interface [sic]
as
Anonymous class is to static initializers (for example)

There is no relationship whatsoever (other than, of course, that they are
all constructs in the Java 2 Programming Language).

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
T

Tony Morris

Actually, I was unaware at the time that anonymous classes could subclass
other classes at all--I had only ever seen and used them with interfaces.
My point was only that it is not necessary to have a named class in order to
get an object that implements a particular interface.

Thanks for the civility,
Matt Humphrey (e-mail address removed) http://www.iviz.com/

An anonymous class ALWAYS subclasses/implements some other class/interface.
- An anonymous class must be instantiated at the time it is declared.
- An anonymous class must always be a local inner class.

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
A

Adam

Tony Morris said:
in order
to

An anonymous class ALWAYS subclasses/implements some other class/interface.
- An anonymous class must be instantiated at the time it is declared.
- An anonymous class must always be a local inner class.

Local? Do you mean that it has to be defined within some method
body? Can't agree here.

Adam
 
T

Tony Morris

Local? Do you mean that it has to be defined within some method
body? Can't agree here.

Adam

Apologies for the ambiguity.
An anonymous class can not be declared as a top level class, that is, it
must be an inner class.
It may be method-local, constructor-local, initialiser-local, or a class
data member.


--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
C

Chris Smith

Tony said:
The only reason I pointed it out is because I interpreted it exactly as you
did, however, it is still incorrect.
That is, "This is not strictly true, but can loosely be thought of it being
so" is incorrect, because it can't even be "loosely thought of as being so".

Perhaps so and perhaps not. I tend to think that from the perspective
of Rajarshi's post, you're right that the similarity of instantiating an
anonymous inner class and "instantiating an interface" wouldn't be
interesting. However, under a different interpretation of the question
-- one of frustration at the amount of syntax needed to accomplish a
task -- pointing to anonymous inner classes as a way of accomplishing
something like instantiating an interface is entirely appropriate.

Fact is, we all make assumptions all the time about the intent of those
who post here. Sometimes we're right, and sometimes we're wrong. Only
the OP can say for sure, and Rajarshi seems to have disappeared from
this thread.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
D

Dale King

Tony Morris said:
The only reason I pointed it out is because I interpreted it exactly as you
did, however, it is still incorrect.

Yes, it is not strictly true, which is immaterial given the "in a manner of
speaking" disclaimer.
That is, "This is not strictly true, but can loosely be thought of it being
so" is incorrect, because it can't even be "loosely thought of as being
so".

Let's go back and review exactly what was said:

Tony Morris said:
Also, don't forget that an interface

No it can't - an interface can never be instantiated.
This is an anonymous inner class that implements the Runnable interface.

Matt's statement can loosely thought of as being true. It depends on how you
define "instantiating". All you have pointed out is that it does not agree
with the technical definition in the JLS. Matt already acknowledged that by
his disclaimer. He is using a looser definition.

You can loosely think of it as creating an instance of an interface. Of
course that is not literally what happens. You are of course creating an
anonymous class, but Matt already acknowledged that. Essentially you get an
object instance that implements the interface without creating a named
class. That can loosely be thought of as though you are instantiating the
interface, even though it is not strictly true.
My example regarding anonymous classes and named classes highlights this
fact. There is no relationship to "subclassing an interface" and the given
example in any way, shape or form. The Java 2 Language Specification also
makes this clear.

That the reason for Matt's disclaimer that it is only in a manner of
speaking. That manner of speaking is not the same manner of speaking as the
JLS.

I plan to drop this issue now as continuing it is not in anyone's best
interest. We already agree on the technical issues and are just arguing over
the meaning of words, which is usually pointless unless we have agreed upon
definitions and we obviously do not agree on certain definitions like what
"in a manner of speaking" means.
 
D

DreamCoder

Abstract class and subclassing is vertical hierarchy , interface some
kind of horizontal hierarchy.
Use abstract when you needs to define variables or some hook or
template method
(non-abstract methods).
Use interface when you only want to define method (abstracts ones).
Another thing , remeber that java permit only one super class.
 
T

Tony Morris

We already agree on the technical issues and are just arguing over
the meaning of words, which is usually pointless unless we have agreed upon
definitions and we obviously do not agree on certain definitions like what
"in a manner of speaking" means.

While you may be right in some respects, I cannot agree with this when the
topic is related, in any way, to computer programming. I teach Java (and
other things) at the local university - to make ambiguous, and in this case,
clearly incorrect, statements will confuse a lot of people. Do mammals lay
eggs "in a manner of speaking" ? Totally ambiguous (although there are two
mammals that DO lay eggs. aka monotremes) - if one didn't know better, what
is the answer to this question ?

I have made the effort to disprove that "instantiating an interface" is not
only syntactically incorrect, but a completely flawed methodology of
thinking, EVEN in a "manner of speaking".
An analogy to "instantiating an interface in a manner of speaking" is to
suggest that "constructors fly airplanes" - it makes no sense at all. I will
admit, however, that to the untrained eye, the syntax of declaring an
anonymous class that implements interface I "looks like" you may be
instantiating I (I can't find an analogy to point this out), but it doesn't,
and it's not even close to it, not even "in a manner of speaking".

Since you seem to have the same misunderstanding, let's sort this out.
Please answer the following:

// Case 1
class X
{
void m()
{
// Is this "instantiating a class X" ? ( "in a manner of speaking"
of course)
X x = new X()
{

};
}
}

// Case 2
interface I
{

}

class A
{
void m()
{
// I assume you think that this is "instantiating an interface (\"in
a manner of speaking\")"
I i = new I()
{

}
}
}

// Case 3
class B implements I
{
void m()
{
// is this "instantiating an interface" ("in a manner of speaking")
?
B b = new B();
}
}

// Case 4
class D
{
void m()
{
// is this instantiating an interface ("in a manner of speaking") ?
i.e. java.util.Comparable, java.io.Serializable
s = "blah";
// or this ?
s = "new String("blah");
}
}

// Case 5
class E
{
void m()
{
// is this instantiating an interface ("in a manner of speaking") ?
new AnyClassThatImplementsAnyInterfaceInTheEntireCoreAPI();
}
}


--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform
 
D

Dale King

Tony Morris said:
We already agree on the technical issues and are just arguing over

While you may be right in some respects, I cannot agree with this when the
topic is related, in any way, to computer programming. I teach Java (and
other things) at the local university - to make ambiguous, and in this case,
clearly incorrect, statements will confuse a lot of people. Do mammals lay
eggs "in a manner of speaking" ? Totally ambiguous (although there are two
mammals that DO lay eggs. aka monotremes) - if one didn't know better, what
is the answer to this question ?

Then it is perfectly valid to say that manner of speaking is likely to
confuse others, but that is not what you did. I would agree that it probably
is confusing to think that way.

A similar example that I have talked about many times here is the endless
topic of whether Java passes objects by value or reference. Of course the
technical answer is that Java never actually passes objects at all. One can
have a mindset that objects are actually passed and this will work in 95% of
the cases. People then come up with exceptions to explain the exceptions. As
I and others point out it is more confusing to have that mind set than just
learn it correctly.
I have made the effort to disprove that "instantiating an interface" is not
only syntactically incorrect, but a completely flawed methodology of
thinking, EVEN in a "manner of speaking".

And failed because it is a question over the meaning of words.
Since you seem to have the same misunderstanding, let's sort this out.

Sorry, I have no misunderstanding here. I understand exactly what Mat meant
and what you meant. I just thought your response to an obviously
non-technical, loose explanation was uncalled for. I am certainly not saying
that it is instantiating in the technical sense of the word.
Please answer the following:
// Is this "instantiating a class X" ? ( "in a manner of speaking"

Let me answer with a question. Is this froobitzking the class X (in a manner
of speaking)? Can you answer that without knowing the definition of
froobitzking? Is there any meaning to your answer to the question if you
have a different meaning you ascribe to froobitzking? All you have pointed
out is that according to the technical definition, this is not froobitzking.
Given the disclaimer it is assumed that he is not using the technical
definition.

So what is the technical definition according to the JLS? According the JLS,
"We say that a class is instantiated when an instance of the class is
created by a class instance creation expression." I agree that by that
definition is not instantiating class X.

Let me rephrase Matt's statement. First let me change it from passive voice
to active voice first so I can make a proper substituting. Here it is in the
active voice:

Also, don't forget that you can also instantiate (in a manner of
speaking) an interface on the fly via an anonymous class

I haven't changed anything except change it from passive to active to make
it easier to substitute in grammatically. OK, now let me substitute in the
looser definition of instantiate that I think Matt was using:

Also, don't forget that you can also [create an object instance whose
type is that of] an interface on the fly via an anonymous class.

I dropped the disclaimer, because that statement is true even by the JLS.
The distinction here is between the use of the word type as opposed to class
see section 4.5.6 of the JLS. You are creating an object that is compatible
with the interface type, but it is not of the class of the interface.

So the manner of speaking that Matt is using is one that blurs the
distinction between the class of an object and the type of the expression.
In the case of an anonymous class the distinction is already blurred. I
would venture to say that the distinction is not that clear in the minds of
many Java programmers.

So in that manner of speaking Matt is correct. Whether that manner of
speaking is the best choice is a separate question.
 

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,888
Messages
2,569,964
Members
46,294
Latest member
HollieYork

Latest Threads

Top