Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2007

Tip: Looking for answers? Try searching our database.

Question about Abstract classes and Interfaces

Thread view: 
imenalo@menalo.ca - 11 Dec 2007 15:14 GMT
Hello,

This is my first post and I'll try to make it as clear as possible.
I'm relatively new to Java, having a wonderful time learning the
language.  One thing I do have trouble seeing in my mind is the use of
Interfaces and abstract classes.

The question I have regarding interfaces is, what exactly is the main
benefit to them.  All the books or pages I read about the topic don't
explain it to the point where I fully understand the benefit.  The
examples I see most are:

<<interface>>
HasArea
-------------------
+ getArea() double

Rectangle, Cylinder and Circle classes all implement the interface.
Therefore, they have to provide a method body for getArea().  I guess
my question remains, what use is the interface (other then applying a
rule like the one above), if all the clients (users of that interface)
need to apply their own implementation?  I mean the only other benefit
I see is the ability to do the following:

HasArea shape = new Rectangle(3, 4); // or some such, makes it
convenient to track all objects that implement the interface.

Secondly, about Abstract classes.  The one question I have about them
is, we can't instantiate an abstract class, but we can get an instance
to it.  Using an example, we can either:

Calendar cal = new GregorianCalendar(); // use the subclass
or Calendar cal = Calendar.getInstance(); // use the factory method

The question I have, if we can't instantiate the class, what exactly
is the second implementation returning?  It can't be a calendar object
can it?  I mean the first one returns the reference to a
GregorianCalendar object.  I just have no clue what the second one
will point to exactly.

Anyways, that's about it.  Thanks in advance and have a great day.

Momar
Patricia Shanahan - 11 Dec 2007 17:13 GMT
> Hello,
>
> This is my first post and I'll try to make it as clear as possible.
> I'm relatively new to Java, having a wonderful time learning the
> language.  One thing I do have trouble seeing in my mind is the use of
> Interfaces and abstract classes.

The main use is to establish a contract defining the relationship
between the uses of a class and its implementation. On average, classes
are used more often than they are implemented - every class should have
at least one use, or it should not exist. Some classes have many uses.
Look at these things more in terms of what they mean to the users of the
class than to the implementation.

> The question I have regarding interfaces is, what exactly is the main
> benefit to them.  All the books or pages I read about the topic don't
[quoted text clipped - 15 lines]
> HasArea shape = new Rectangle(3, 4); // or some such, makes it
> convenient to track all objects that implement the interface.

More than that, you can call operations such as getArea without knowing
about the individual implementation, just the contract represented by
the HasArea interface.

> Secondly, about Abstract classes.  The one question I have about them
> is, we can't instantiate an abstract class, but we can get an instance
> to it.  Using an example, we can either:
>
> Calendar cal = new GregorianCalendar(); // use the subclass
> or Calendar cal = Calendar.getInstance(); // use the factory method

Java makes two, very different, uses of class names, to name the actual
class of an object, and to name the type of an expression. The class of
an object is determined when it is created, and never changes. "new
GregorianCalendar()" references a newly created instance of the
GregorianCalendar class.

"Calendar cal" does not limit cal to referencing an instance of the
Calendar class. It only promises that any object cal references can be
treated as a Calendar, either because it is actually one, or because its
class extends Calendar. Similarly, Calendar.getInstance() is a Calendar
type expression, which must either be null or reference an object that
can be treated as a Calendar.

Patricia
Steve W. Jackson - 11 Dec 2007 17:31 GMT
In article
<d9640e0d-dbb8-41b4-8a5b-d5ee453b14d0@y5g2000hsf.googlegroups.com>,

> Hello,
>
[quoted text clipped - 22 lines]
> HasArea shape = new Rectangle(3, 4); // or some such, makes it
> convenient to track all objects that implement the interface.

I think of an interface as a way to make any object fit the "is a"
definition.  Since Circle implements HasArea, then Circle "is a" HasArea
and can be passed as a parameter anywhere a HasArea is accepted.  More
generally, in this case, anything representing a geometric shape that
has an area should implement it so that you can ask for the area.

> Secondly, about Abstract classes.  The one question I have about them
> is, we can't instantiate an abstract class, but we can get an instance
[quoted text clipped - 12 lines]
>
> Momar

You can not directly instantiate the abstract class.  But as a defined
class, you can use its name to refer to any instance of a subclass.  
That's similar to the way that an instance of any class could be
referred to as Object, since java.lang.Object is the base class of the
entire class hierarchy in the language.  When reading the Javadocs,
you'll note that the inheritance tree of the class being viewed always
goes back to Object.

The two examples above demonstrate different things.  GregorianCalendar
is a concrete subclass of Calendar and has a constructor you can use to
create one.  As a subclass of Calendar, you *can* refer to it as such.  
The second, however, shows that the Calendar class, while abstract,
contains a static "factory method" which will create an instance some
concrete subclass and return it to you.  If you wanted, you could take
that "cal" variable and call "cal.getClass().getName()" to find out the
package-qualified name of the concrete subclass, which may even be in
some package you can't access yourself.

Aside from that, however, the most common use of abstract classes is to
form an outline so that developers using some API you provide would be
required, if they want to use instances of your class, to create
subclasses containing implementation of methods you specify.  I'm
allowed to implement a Calendar subclass if I like, and I *must*
implement the abstract methods or other members or I can't use it like
any other Calendar...but in this particular case, it's not done often
since the most commonly used Calendar types are available on a
per-locale basis via static factory methods.

= Steve =
Signature

Steve W. Jackson
Montgomery, Alabama

Philipp - 11 Dec 2007 17:42 GMT
> Calendar cal = new GregorianCalendar(); // use the subclass
> or Calendar cal = Calendar.getInstance(); // use the factory method
[quoted text clipped - 4 lines]
> GregorianCalendar object.  I just have no clue what the second one
> will point to exactly.

This is the whole point in using a factory method. The programmer of the
library chose to *not* let you know exactly which type (ie subclass) of
Calendar he is serving you. The choice is done inside the factory method
based on some other informations (in this case the locale).

FYI, you can go look inside the code if you're curious (see below)...
What you see, is that in some countries (eg. Japan) the returned
Calendar will be different.

HTH
Phil

(below copyright Sun)

public static Calendar getInstance()
{
  Calendar cal = createCalendar(TimeZone.getDefaultRef(),
Locale.getDefault());
  cal.sharedZone = true;
  return cal;
}

private static Calendar createCalendar(TimeZone zone, Locale aLocale)
{
  // If the specified locale is a Thai locale, returns a BuddhistCalendar
  // instance.
  if ("th".equals(aLocale.getLanguage())
      && ("TH".equals(aLocale.getCountry()))) {
      return new sun.util.BuddhistCalendar(zone, aLocale);
  } else if ("JP".equals(aLocale.getVariant())
       && "JP".equals(aLocale.getCountry())
       && "ja".equals(aLocale.getLanguage())) {
      return new JapaneseImperialCalendar(zone, aLocale);
  }

  // else create the default calendar
        return new GregorianCalendar(zone, aLocale);
}
imenalo@menalo.ca - 11 Dec 2007 17:50 GMT
Thanks for the replies.  I can now understand the abstract class
better, and even the interface.  Could you give me a real world
example, or some type of example that shows the benefits of having an
interface as opposed to an abstract class or just regular
inheritance.  I mean in all the examples I tend to see, the same thing
can be accomplished with classes.

Thanks again for both replies, I saved them in a text file to re-read
when I need :)
imenalo@menalo.ca - 11 Dec 2007 17:55 GMT
On Dec 11, 12:50 pm, imen...@menalo.ca wrote:
> Thanks for the replies.  I can now understand the abstract class
> better, and even the interface.  Could you give me a real world
[quoted text clipped - 5 lines]
> Thanks again for both replies, I saved them in a text file to re-read
> when I need :)

Heh, I didn't know the code like that was available anywhere.  It
follows the quick test I did though which was outlined by Steve:
cal.getClass().getName()
Which did return a GregorianCalendar.  Are there factory methods for
Iterators as well?
Robert Klemme - 11 Dec 2007 22:38 GMT
> On Dec 11, 12:50 pm, imen...@menalo.ca wrote:
>> Thanks for the replies.  I can now understand the abstract class
[quoted text clipped - 3 lines]
>> inheritance.  I mean in all the examples I tend to see, the same thing
>> can be accomplished with classes.

A very nice example of interface usage are all the JEE standards, e.g.
JDBC to name a very common one.  Since JDBC drivers are provided by
different vendors and there is likely no code that implementations could
share, interfaces are better here than abstract classes.  Abstract
classes really only make sense if they actually contain method
implementations.  If they do not, an interface is much better because it
does not restrict inheritance of classes that implement it.

>> Thanks again for both replies, I saved them in a text file to re-read
>> when I need :)
[quoted text clipped - 4 lines]
> Which did return a GregorianCalendar.  Are there factory methods for
> Iterators as well?

Every java.util.Collection is a factory for java.util.Iterator instances.

Kind regards

    robert
Lew - 12 Dec 2007 03:20 GMT
imenalo@menalo.ca wrote:
>>> Could you give me a real world
>>> example, or some type of example that shows the benefits of having an
>>> interface as opposed to an abstract class or just regular
>>> inheritance.  I mean in all the examples I tend to see, the same thing
>>> can be accomplished with classes.

java.util.Collection

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.