Help OOP runtime selection and instantiation of objects
Hi, I have I am trying to create a program for my lecturer, who has asked me to create an application containing a number of different class that all inherit from an abstract class.
This has been completed and encapsulated, however in writting the application that utilises these classes I have run into an issue.
The application will carry out the same routines regardless of the users choice of class. However as each class has different methods I can not see how to cast between a public object to the chosen cast.
ie the user selects one of the classes to use
class A
class B
class C
the user may select class B however the app would carry out the same procedures.
thinking i could just cast between the public object and an instance of the required class I tryed
public object userChoice;
B chosenClass = new B();
userChoice = chosenClass;
this will not compile, please can anyone point me in the correct direction.
FallenPaladin
Junior Poster in Training
62 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2
The classes would need to share a parent to do that and all be descended from the parent
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
Hi thanks for your reply.
I am unsure what you mean by parent. All of the classes avalible to be selected by the user all use the same base abstract class. However the constructor of each changes the values of the fields within the base in a different manner and aslo have different methods avalible for use.
The global object I wish to base the application code on reports that it is of the correct type, however I am unable to access any of the required members.
FallenPaladin
Junior Poster in Training
62 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2
All your 3 options would have to descend from the same class. Much as you descend from your parents, classes descend from things, currently if you say nothing else TObject. So while you could then cast your tobject and assign an instance of your item, it would be hard to work with.
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
--> public object userChoice; declaration of an object
--> B chosenClass = new B();
--> userChoice = chosenClass; use of object without instantiation
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
userChoice = chosenClass; use of object without instantiation
More like, syntax error.
FallenPaladin why don't you paste some representative code to show exactly the kind of thing you're trying to do?
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
Hi
Thank you all for your time. and, with your help I have managed to solve the problem.
FallenPaladin
Junior Poster in Training
62 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2