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 / June 2006

Tip: Looking for answers? Try searching our database.

A simple question for Abstract Class

Thread view: 
Leo Smith - 26 May 2006 16:46 GMT
Dear All,

I am confused about Abstract Class. I know Abstrac Class is a class
contains > 1 abstract methods. I know Abstract Class can only be used as
a base class and cannot have instances of it.

What I am not clear is: if A is the abstract class, which has two
abstract methods.
public abstract class A
{

    public abstract void method_1();
   
    public abstract void method_2();

}

public class B extends A
{
    public void method_1() {
        //implementation
    }
    //but not implementing method_2()
}

Is B an abstract class? Can B has objects of its own? My foggy impresion
is that B can have objects of its own. B is not an abstract class either.

Am I correct? Thank you.
Thomas Hawtin - 26 May 2006 17:01 GMT
> I am confused about Abstract Class. I know Abstrac Class is a class
> contains > 1 abstract methods. I know Abstract Class can only be used as
> a base class and cannot have instances of it.

Since 1.1 abstract classes have not needed any abstract methods. Take
for instance, java.awt.event.MouseAdapter. This differs from C++, where
an abstract class is one with at least one pure virtual method (often
the destructor, which should also have an implementation).

> public abstract class A
> {
[quoted text clipped - 15 lines]
> Is B an abstract class? Can B has objects of its own? My foggy impresion
> is that B can have objects of its own. B is not an abstract class either.

You will need to declare B abstract.

However, if you compile both classes with A not having method_2, and
then recompile A only with both abstract methods, then you'll get a
mess. It will load okay, but you'll get an AbstractMethodError if you
try to call method_2 on a B. The only place you are likely to see this
deliberately done is in java.sql, which regularly adds methods to
interfaces.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Mariano2012 - 26 May 2006 17:09 GMT
B is a abstract class, In this way a object of class B can't be
created. You must implements all abstract methods or extend class B.

public abstract class A {
    public abstract void methodA1();
    public abstract void methodA2();
}//EndClass

public abstract class B extends A{
    public abstract void methodB();
}//EndClass

// Class A and Class B can't be created
// because are abstract classes
public class C extends B {
    public void methodA1(){}
    public void methodA2(){}
    public void methodB(){}
}//EndClass

Regards,
Mariano
Leo Smith - 26 May 2006 17:26 GMT
I am not sure you two above are correct. If you two are correct, how to
understand the following:

Just see the top part explanation
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/WindowAdapter.html#window
Closing(java.awt.event.WindowEvent
)

For example, WindowAdapter is an abstract class, which implements
several interfaces(WindowListener, WindowFocusListener,
WindowStateListener, EventListener). Needless to say, WindowAdapter has
a lot of methods ("abstract methods") in it.

If I have a sub-class of WindowAdapter, I can just redefine the methods
I care, no need to worry about other methods. (I don't even know how
many methods and their names in WindowAdapter.)
chris brat - 26 May 2006 17:42 GMT
If any class extends any abstract class it must also be defined as an
abstract class - this is enforced by the compiler.

The classes in the WindowAdapter class are not abstract - the class
itself is.
You cannot instantiate an instance of the WindowAdapter class as is -
you would need to do the following :

public abstract class DummyClass {

   public DummyClass(){
       System.out.println("Dummy class output");
   }

   public void method1(){
      // not abstract but does nothing
   }

   public void method2(){
      // not abstract but does nothing
   }

       public static void main(String[] args) {
           new DummyClass(){
               // override any methods here
               // could override method1() or method2() to give them
               // logic but since they aren't abstract it isn't
necessary
           };
       }
}

You should get the following output (unless I mistyped) :

Dummy class output
chris brat - 26 May 2006 17:57 GMT
sorry, the first sentence doesn't makes sense. It should be

"If any class extends any abstract class and does not implement all the
methods (those defined as abstract or defined by implemented interfaces
) it must also be defined as an
abstract class - this is enforced by the compiler."
Chris Uppal - 26 May 2006 17:45 GMT
> For example, WindowAdapter is an abstract class, which implements
> several interfaces(WindowListener, WindowFocusListener,
> WindowStateListener, EventListener). Needless to say, WindowAdapter has
> a lot of methods ("abstract methods") in it.

WindowAdapter is an abstract class, that's true.  (Though /why/ it's abstract
puzzles me -- I think it's a design error).  But none of the methods defined in
WindowAdapter are abstract, they are all real, concrete methods, with proper
bodies.  None of the methods /do/ anything, but that doesn't make them
abstract.

   -- chris
chris brat - 26 May 2006 17:50 GMT
As far as I know it is for easier coding of window events - you only
override the methods to be processed by your window in an anonymous
class.

Don't think it was a design error but it is still clunky.
Chris Uppal - 26 May 2006 18:20 GMT
> As far as I know it is for easier coding of window events - you only
> override the methods to be processed by your window in an anonymous
> class.
>
> Don't think it was a design error but it is still clunky.

No, I meant: why is the class declared /abstract/ ?  I know what the class
itself is for, and it's a pretty good idea, given the architecture it's part
of.  But there is no good reason to declare it abstract.  Instances would work
/exactly/ as well for all its current applications if it were a concrete class.
/And/ it could be used as a "null" implementation as well (which is
occasionally useful, for testing, and suchlike).

Presumably someone at Sun had a design twitch and confused: "I, having thought
about the matter for about three seconds (but not with any great care), do not
immediately see a reason to use this class without subclassing it", with the
rather different: "it could never be anything other than an error for someone
to use this class without subclassing it".

   -- chris
Juha Laiho - 26 May 2006 20:19 GMT
"Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> said:
>> As far as I know it is for easier coding of window events - you only
>> override the methods to be processed by your window in an anonymous
>> class.
>
>No, I meant: why is the class declared /abstract/ ?
...
>Presumably someone at Sun had a design twitch and confused: "I, having
>thought about the matter for about three seconds (but not with any
>great care), do not immediately see a reason to use this class without
>subclassing it", with the rather different: "it could never be anything
>other than an error for someone to use this class without subclassing it".

Chris;

I'd consider declaring this kinds of classes abstract is a kind of safety
belt. This forces the programmer to make a conscious decision about methods
needed for the current case.

As for your need for the nullobject variant of this, you could have that
just by extending the class and not overriding any of the methods - but
even in that case, it'll be a conscious decision.

Whether this "safety belts" -design is good or not is a different matter;
I won't comment on that. But I guess this is the rationale.
Signature

Wolf  a.k.a.  Juha Laiho     Espoo, Finland
(GC 3.0) GIT d- s+: a C++ ULSH++++$ P++@ L+++ E- W+$@ N++ !K w !O !M V
        PS(+) PE Y+ PGP(+) t- 5 !X R !tv b+ !DI D G e+ h---- r+++ y++++
"...cancel my subscription to the resurrection!" (Jim Morrison)

Andrew McDonagh - 26 May 2006 22:49 GMT
> "Chris Uppal" <chris.uppal@metagnostic.REMOVE-THIS.org> said:
>>> As far as I know it is for easier coding of window events - you only
[quoted text clipped - 17 lines]
> just by extending the class and not overriding any of the methods - but
> even in that case, it'll be a conscious decision.

Yep.

frame.addWindowListener( new WindowAdapter() {} );

Only its not to clear that we have created an anonymous inner class, its
easy to miss the '{}'.

However,....

> Whether this "safety belts" -design is good or not is a different matter;
> I won't comment on that. But I guess this is the rationale.

whilst i agree in principle, I think the confusion stems from the
classes name - WindowAdapter.

If it was called AbstractWindowAdapter, then as a developer I'd see it
as a design choice that the API provider expects us to derive from it in
order to fulfill a desired approach.

Likewise with the NullObject pattern, If there was a derived (final)
class called WindowAdapterNullObject (or something) then its clear that
it has a single purpose.  In fact we could have had the
WindowAdapterNullObject class derive from the AbstractWindowAdapter
class as part of the JDK.
Chris Uppal - 30 May 2006 10:54 GMT
[me:]
> > Presumably someone at Sun had a design twitch and confused: "I, having
> > thought about the matter for about three seconds (but not with any
[quoted text clipped - 5 lines]
> I'd consider declaring this kinds of classes abstract is a kind of safety
> belt.

IMO, the "abstract" doesn't add any safety, it just reduces functionality.  (I
do understand your point, I just don't really agree with it.)

> Whether this "safety belts" -design is good or not is a different matter;
> I won't comment on that. But I guess this is the rationale.

Another possible reason is that the programmer was blindly applying a "rule" of
good design -- don't subclass from concrete classes.  Rules are all very well
if they are applied with discretion, but some programmers forget that following
rules is not a substitute for thinking.

BTW, I don't think the class is at all well named.  It isn't a kind of
adapter at all (though subclasses /may/ be).  It is either conceived as an
abstract framework for creating Listener implementations, in which case it
might be called AbstractWindowListener; or it could be viewed as the root, or
default, implementation of a Listener, in which case NullWindowListener or
BasicWindowListener would be reasonable names.

   -- chris
Luc The Perverse - 30 May 2006 22:25 GMT
>> I'd consider declaring this kinds of classes abstract is a kind of safety
>> belt.
>
> IMO, the "abstract" doesn't add any safety, it just reduces functionality.
> (I
> do understand your point, I just don't really agree with it.)

Hmm - for a novice programmer who doesn't know what he/she is doing,
something like a carefully placed assert or abstract class to prevent them
from doing something wrong can be very helpful.  I have never encountered a
problem like this in Java, but in MSVC++.

--
LTP

:)
Chris Uppal - 31 May 2006 09:59 GMT
[me:]
> > IMO, the "abstract" doesn't add any safety, it just reduces
> > functionality.[...]
>
> Hmm - for a novice programmer who doesn't know what he/she is doing,
> something like a carefully placed assert or abstract class to prevent them
> from doing something wrong can be very helpful.

I agree that safety is a worthwhile goal, I even agree -- with strong
reservations -- that safety is still a worthwhile goal even when the only
direct beneficiaries are people who don't fully understand the language.

What I /don't/ agree with is that declaring WindowAdapter abstract adds any
safety at all.

   -- chris
Dale King - 31 May 2006 14:37 GMT
> [me:]
>>> IMO, the "abstract" doesn't add any safety, it just reduces
[quoted text clipped - 9 lines]
> What I /don't/ agree with is that declaring WindowAdapter abstract adds any
> safety at all.

I think safety is probably a bad word to describe it, but there is some
benefit to a newbie to tell keep them from instantiating a WindowAdapter.

On the flip side, I don't think there is any benefit to not declaring
WindowAdapter abstract. You claim it reduces functionality, but there
really isn't a plausible use for an instance of WindowAdapter.

Signature

 Dale King

Chris Uppal - 31 May 2006 15:35 GMT
> I think safety is probably a bad word to describe it, but there is some
> benefit to a newbie to tell keep them from instantiating a WindowAdapter.

"Safety" wasn't the best choice of word, I agree.

> [...] You claim it reduces functionality, but there
> really isn't a plausible use for an instance of WindowAdapter.

Sure there is.  Once you've got working Null objects (or deaf objects) then
uses crop up all over the place.  E.g. dummying stuff out during development,
debugging, and testing (these form the main uses, IMO).  As a default for
configurable/pluggable architectures.   As "safe" placeholders to replace the
normal listener during updates which could generate unwanted notification. As a
way to avoid ugly if (xxx != null) tests all over the place.  And so on...

Null objects are useful.  The person at Sun writing this class apparently
forgot that.

   -- chris
Luc The Perverse - 02 Jun 2006 01:13 GMT
> Null objects are useful.  The person at Sun writing this class apparently
> forgot that.

Huh?  You can't set abstract objects to null?

I had not looked into this but that doesn't make any sense at all.

I thought the beauty of OOP (transcending language) was being able to write
code like this.

AbstractAnimalClass[] pets = {null, new Dog(), new Cat()};
for(int i=0;i<pets.length;i++)
   if(pets[i]!=null)
       pets[i].speak();  //Make some noise!

--
LTP

:)
Chris Uppal - 02 Jun 2006 11:34 GMT
[me:]
> > Null objects are useful.  The person at Sun writing this class
> > apparently forgot that.
>
> Huh?  You can't set abstract objects to null?

You misunderstand -- which is understandable ;-)

"null objects" have nothing to do with the "null" value in Java.  They are
objects (real, proper, objects) which implement a protocol shared with other
objects (For "protocol" in Java read "interface or type") by performing no
action.

> I thought the beauty of OOP (transcending language) was being able to
> write code like this.
[quoted text clipped - 3 lines]
>     if(pets[i]!=null)
>         pets[i].speak();  //Make some noise!

Yes, sort of.  You have the polymorphism bit down pat, but notice how Java's
null value is /not/ polymorphic with anything.  It's a singularity in the
semantics, and causes a deal of extra work and verbiage.  The same idea
expressed using null objects would look like:

 AbstractAnimalClass[] pets = { new NullAnimal(), new Dog(), new Cat() };
 for (int i = 0; i < pets.length; i++)
   pets[i].speak();

Not a very good example, I admit, but at least it illustrates the absence of
ugly and arbitrary is-null tests.

If you look on the Web for more info, then don't restrict your search to
Java --  it's not a language-specific concept.  Indeed, it seems to be rarely
used in Java; I don't know to what extent that's because Java's inflexible type
system makes it awkward, or because (speaking statistically /only/ !) Java
programmers tend to be relatively unsophisticated.

   -- chris

P.S.  On re-reading this, I should perhaps make it clear that I'm not
advocating a wholesale replacement of Java's null value with null objects!
Dale King - 03 Jun 2006 16:41 GMT
>> [...] You claim it reduces functionality, but there
>> really isn't a plausible use for an instance of WindowAdapter.
[quoted text clipped - 8 lines]
> Null objects are useful.  The person at Sun writing this class apparently
> forgot that.

Null objects are useful. The greatest use for them is for subclassing
and having default implementations.

There are also uses for instances of null objects. Mostly in cases where
you are required to provide an implementation of an interface to use an
API. When the use of the interface is completely optional there is not
as much use.

In the case of WindowAdapter I can't see any great use for them. There
is no reason to actually add one as a listener to a window, because it
is the same as not adding anything.

But let's say you do need a do nothing implementation of WindowAdapter.
Then the fact that they made it abstract is only the difference between
these two expressions, which is not rally valid to claim as a "reduction
in functionality"

    new WindowAdapater()

vs.

    new WindowAdapater() {}

Signature

 Dale King

Dale King - 27 May 2006 16:00 GMT
>> As far as I know it is for easier coding of window events - you only
>> override the methods to be processed by your window in an anonymous
[quoted text clipped - 14 lines]
> rather different: "it could never be anything other than an error for someone
> to use this class without subclassing it".

I can't really come up with a very likely scenario where you would
really need an implementation of WindowAdapter that did nothing. If you
don't need the window events then don't register a listener for them.
The closest I can come up with is a state pattern where you have a
window listener that forwards on events to a different listener
depending on state and in one of those states you are to ignore the events.

You are right that there was no *need* for it to be abstract. But one
could make a case for saying it was a way to send a message to someone
that didn't quite know what they were doing that they are probably doing
something wrong by instantiating this class.

So it would be difficult to make a case for saying that it harms anyone
by making it abstract and one could make a case for it being helpful to
make it abstract.

Signature

 Dale King

Prem - 05 Jun 2006 11:04 GMT
Could it be a language design issue, rather than a design error? I mean
if WindowAdapter had not been abstract, we would have been able to
instantiate objects of that type - objects whose methods did absolutely
nothing. Does this imply something that goes against the inherent
object-orientedness of java in some way? Or could it result in more
potential runtime errors ?

> WindowAdapter is an abstract class, that's true.  (Though /why/ it's abstract
> puzzles me -- I think it's a design error).  But none of the methods defined in
[quoted text clipped - 3 lines]
>
>     -- chris
Chris Uppal - 05 Jun 2006 11:26 GMT
> if WindowAdapter had not been abstract, we would have been able to
> instantiate objects of that type - objects whose methods did absolutely
> nothing. Does this imply something that goes against the inherent
> object-orientedness of java in some way? Or could it result in more
> potential runtime errors ?

No to both, I think.

How an object behaves when sent a message (when a method is invoked) is /it's/
affair, not anyone else's -- providing that it meets the terms of whatever
formal or informal contracts make up the overall design.  If it does nothing
(and if doing nothing is allowable in the specific circumstances), then that's
valid and natural OO.  Just another object doing its own job in its own way.

   -- chris
Andrew McDonagh - 05 Jun 2006 19:25 GMT
> Could it be a language design issue, rather than a design error? I mean
> if WindowAdapter had not been abstract, we would have been able to
[quoted text clipped - 10 lines]
>>
>>     -- chris

No, it would just be a miss named class.

It would be better named NullObjectWindowAdapter - or some such, to
highlight that the class was implementing the NullObject design pattern.

See http://www.industriallogic.com/xp/refactoring/nullObject.html
Roedy Green - 26 May 2006 17:47 GMT
>I know Abstrac Class is a class
>contains > 1 abstract methods.

Not necessarily.  Oddly you can declare a class abstract even though
all its method bodies  are defined. The idea is you have to extend the
class to use it.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 26 May 2006 17:49 GMT
>public class B extends A
>{
[quoted text clipped - 6 lines]
>Is B an abstract class? Can B has objects of its own? My foggy impresion
>is that B can have objects of its own. B is not an abstract class either.

If you implement all the abstract methods of the base class, and don't
declare the new class abstract then it is not abstract. The new class
can also have its own fields and methods.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

yeraycaballero@gmail.com - 27 May 2006 22:14 GMT
I don't understand you, but I can eplain you this concepts.

- An Abstract class is a class that can't be instanced. An Abstract
class can have 0 or more abstract methods. if you have an abstract
class A which has abstract methods and a class B which extends A, you
would have to implements all this methods.

"An abstract method on super class force you to implement this on child
classes."

In your case

public class B extends A
{
       public void method_1() {
               //implementation
       }
       //but not implementing method_2()
}

you will have to implement method_1() and method_2(), and you could
create instances of B class because B is a concrete class.


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.