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

Tip: Looking for answers? Try searching our database.

Creating objects.

Thread view: 
Stofdeel - 11 May 2006 13:20 GMT
Hello,

I have an abstract base class (MyBase).
I have a collection class for the abstract base class (MyCol). MyCol extends
AbstractList<MyBase>.
I have child classes (MyChildA, MyChildB). MyChildA/B extend MyBase.

I want to create MyChildA/B objects inside a MyCol method and add them to
the collection. At design time I know MyChildA/B extend MyBase but only at
runtime I know if it will be A or B (or C or D or E...).

Is there anyway to pass the class type as a paremeter to the method that
creates the objects, and then use the parameter to create the objects of the
correct type? And can this be done by using only 'default' java libraries?
If there is such a thing.

I am using NetBeans IDE 5.0, Java 1.5.0_06.

Thanks for any information.
chris brat - 11 May 2006 13:35 GMT
This seems to be a very complicated way to add objects to a list.

Why not do this

// create a list - standard Java utils
List<MyBase> myCol = new ArrayList();        // can be any impl of List
interface.

// create the objects you need
MyBase obj1 = new MyChildA();
MyBase obj2 = new MyChildB();

// add to the list
myCol.add(obj1);
myCol.add(obj2);

// retrieve the objects you need - could be either MyChildA or MyChildB
instance
MyBase retrieved = myCol.get(1);

// work on the retrieved object

Why do you want to extend AbstractList ? What functionality are you
wanting to add?

Chris
Stofdeel - 11 May 2006 13:57 GMT
Heya Chris,

I can't create objects the way you describe, because I don't know the type
at design time. In the .NET (MS) environment I can have a string (with a
name of a type) which I can use to create an object of type 'System.Type'.
With this object I can create an instance of the type it represents (as long
as the correct library is linked), using a function called
'CreateInstance(type, parameters)'. I was hoping for something similar in
java, but I am having trouble finding an answer to this question on the
internet.

The collection class will get extra functionality. Default one won't do. I
think I am extending the correct one because it does everything is it
suppose to do.

Thanks for the repsonse.

> Why not do this
>
[quoted text clipped - 20 lines]
>
> Chris
chris brat - 11 May 2006 14:12 GMT
This can be done.

Look at the java.lang.Class api - specifically the forName() and
newInstance() methods.

The class name must be the fully qualified class name (i.e. including
the package name).

I recommend that if you are going to be creating objects of classes at
runtime this way, then make the classes extend a base class or
implement a common interface so that you can store them in a collection
in the way I described before.

Again, what new functionality do you want to add to the list?
Stofdeel - 11 May 2006 14:41 GMT
Great! That sounds like the thing I need.

The extra functionality for the collection class? It has nothing to do with
my topic, but basicly what it does is call functionality of other classes.
For example, there are other classes that handle the graphical user
interface (windows and stuff). The collection has a method to show itself in
a default window.

> This can be done.
>
[quoted text clipped - 10 lines]
>
> Again, what new functionality do you want to add to the list?
Robert Klemme - 11 May 2006 16:54 GMT
> Great! That sounds like the thing I need.
>
[quoted text clipped - 3 lines]
> interface (windows and stuff). The collection has a method to show itself in
> a default window.

Now this sounds really spooky: you're mixing collection, factory *and*
UI code in a single class.  Really, rather do separate these concerns.

My 0.02 EUR

Kind regards

    robert
Bjorn Abelli - 11 May 2006 13:53 GMT
"Stofdeel" wrote...

> I have an abstract base class (MyBase).
> I have a collection class for the abstract base class
> (MyCol). MyCol extends AbstractList<MyBase>.
> I have child classes (MyChildA, MyChildB). MyChildA/B extend MyBase.

That means that any instance of the subclasses also will fit into the
collection.

> I want to create MyChildA/B objects inside a MyCol method and
> add them to the collection.

I see that as a bit odd approach. Not impossible, but odd, as you then
combine MyCol into not only a collection class, but also a factory class
(speaking in pattern terms).

Maybe I'm too strict in my use of OO, but I see benefits in separating the
concerns of different classes. Why not make a separate singleton factory
class?

> At design time I know MyChildA/B extend MyBase but only
> at runtime I know if it will be A or B (or C or D or E...).

I interpret that as that MyCol will "know all subtypes of MyBase", which
could induce problems in the future (another reason to separate that task to
another class).

> Is there anyway to pass the class type as a paremeter to
> the method that creates the objects, and then use the
> parameter to create the objects of the correct type?
> And can this be done by using only 'default' java libraries?
> If there is such a thing.

Sure, a simple "if" will suffice, where you test against the Class instance
you send in.

Class c = ...;
MyBase x = null;

if (c.Name.equals("MyChildA") )
{
  x = new MyChildA();
}
...

Or, you could simply use reflection:

MyBase x = (MyBase) c.newInstance(...);

On the other hand, if the caller already knows what Class it has, it could
also call separate methods which creates an instance from a specific class.

// Bjorn A
Stofdeel - 11 May 2006 14:49 GMT
Heya.

> Maybe I'm too strict in my use of OO, but I see benefits in separating the
> concerns of different classes. Why not make a separate singleton factory
> class?

Because I won't need the functionality anywhere else. I know, one can't know
this, but I am pretty sure. But a seperate class could be a posibility.

> > At design time I know MyChildA/B extend MyBase but only
> > at runtime I know if it will be A or B (or C or D or E...).
>
> I interpret that as that MyCol will "know all subtypes of MyBase", which
> could induce problems in the future (another reason to separate that task to
> another class).

No it won't. There can and probably will be a lot of different MyChild's.

> Or, you could simply use reflection:
>
> MyBase x = (MyBase) c.newInstance(...);

Yes indeed something like that, and then a paremeter with the type of the
class. I am gonna try this "java.lang.Class" api.

Thanks for the (quick) responses.
Chris Smith - 11 May 2006 14:59 GMT
> I want to create MyChildA/B objects inside a MyCol method and add them to
> the collection. At design time I know MyChildA/B extend MyBase but only at
> runtime I know if it will be A or B (or C or D or E...).

Yep.  You want a parameter of type Class.  Since you're using 1.5
(exception handling omitted):

   public void theMethod(Class<? extends MyBase> type, ...)
   {
       MyBase theObj = type.newInstance();
       ...
   }

(If there are constructor args, you would call getConstructor(Class[])
and then newInstance(Object[]) of the Constructor object, instead.  The
code above will look for a constructor with no arguments.)

If you intend to return the new object and want to do it in a type-safe
way, you can do this:

   public <T extends MyBase> T theMethod(Class<T> type, ...)
   {
       T theObj = type.newInstance();

       ...

       return theObj;
   }

and then,

   MyChildA child = theCol.theMethod(MyChildA.class);

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Robert Klemme - 11 May 2006 16:55 GMT
>> I want to create MyChildA/B objects inside a MyCol method and add them to
>> the collection. At design time I know MyChildA/B extend MyBase but only at
[quoted text clipped - 28 lines]
>
>     MyChildA child = theCol.theMethod(MyChildA.class);

Even more flexible alternative: use the factory pattern, i.e. define an
interface that has a method, say "public MyBase create()" and implement
several factory classes for this.

Kind regards

    robert
chris brat - 11 May 2006 17:11 GMT
Abstract factory pattern?

..... yummy.


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.