Re: Creating funny objects

From: Michael Borgwardt (brazil_at_brazils-animeland.de)
Date: 12/06/04


Date: Mon, 06 Dec 2004 11:51:35 +0100

hopkins wrote:
> In particular, why are objects created like this
>
> SAXParserFactory factory = SAXParserFactory.newInstance();
> ...and
> SAXParser saxParser = factory.newSAXParser();
>
> I have always been taught to creat object in the form
>
> Person newPerson = new Person();
>
> This way where you seem to call a different method other than the
> constructor when the object is created confuses me and I cant really
> understand why you'd want to do this.

This is known as a factory method. Paul gave an example why one might
want to do this.

Basically, it's more flexible than a constructor, because a constructor
can only "return" an instance of the concrete class, while a factory can
declare an abstract class or an interface as its return type and return
an arbitrary subclass or intrface implementation. Note that in your
code, SAXParser is an abstract class, so it's not possible to instantiate
it with "new".

> Secondly as the two lines in
> question dont seem to have the "new" keyword does this mean they are
> not created on the heap and are stack based like in C++?

No. The factory method will use "new" in some way, directly or indirectly.



Relevant Pages

  • Re: Factory method
    ... > factory method in my abstract class that creates subclasses. ... > constructor in my subclasses must be able to call the constructor in my ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Factory method
    ... > factory method in my abstract class that creates subclasses. ... > constructor in my subclasses must be able to call the constructor in my ...
    (microsoft.public.dotnet.languages.csharp)
  • Factory method
    ... I have an abstract class, and a set of classes that inherit from my abstract ... factory method in my abstract class that creates subclasses. ... constructor in my subclasses must be able to call the constructor in my base ... For the factory method in my abstract class to call the constructor ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: My LogGenerator.java wont compile - too many errors - help
    ... I meant static factory method, it's what you implemented to replace the ... constructor that you made private. ... Consider the singleton pattern. ...
    (comp.lang.java.help)
  • Re: Could an object refuse to be created!?
    ... that you might instead use a factory method. ... also capable of returning null rather than throwing an exception. ... > Hi Kevin, ... throw an Exception in the object's constructor. ...
    (microsoft.public.dotnet.languages.csharp)