Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Abstract classes

 
Karan Rajan
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding of the purpose of abstract classes is that the abstract classes let you define some behaviors; they force your subclasses to provide others.

Now, an abstract class need not have any abstract methods. So if we do have an abstract class without any abstract methods then we will not be forcing a subclass to override any method.

So why would we want to have an abstract class without any abstract methods ?
I noticed this as I was doing some reading on HttpServlet class. The HttpServlet class is an abstract class without any of its methods being abstract.

Many thanks.
 
Kamal Ahmed
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It�s possible to declare a class as abstract without including any abstract methods. This is useful when you�ve got a class in which it doesn�t make sense to have any abstract methods, and yet you want to prevent any instances of that class.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the class were not abstract, then a developer may be tempted to use it as is. But in the case of HttpServlet, at least one of its methods must be overridden (usually doGet() or doPost()). So, my guess is that Sun is forcing a developer to subclass HttpServlet who, in doing so, is then more likely to do the right thing and override the appropriate method(s).
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are some abstract DefaultWhatever classes in Swing. They implement all the methods required by the Whatever interface, but all the methods do nothing. You can extend this class to override any methods you need with less effort than implementing all the methods in the interface. It feels like cheating somehow, but it's very handy.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

A bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Initials aren't enough. You can change your display name here. Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic