dcsimg
Calling methods in subclass from main method
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Mark_Grech
Posted On:   Tuesday, March 19, 2002 09:56 AM

I have been trying to solve this problem for hours and I would appreciate should somebody be kind enough to offer me a solution. I have a class named Person and a subclass of this named Worker. In the main method I am defining an array as: Person myPersons[] = new Person[N]; that is an array of objects of class Person. Some of the objects inside this array extend to the class Worker. In class worker I have a very simple method getwGroup() that reads and returns a particular value from within the array that belongs to the class Worker. I am trying to access this method from a method inside the main method as follows: wgroup = ancestPerson.getwGroup(); where ancestPerson is of type Person and is defines in the m   More>>

I have been trying to solve this problem for hours and I would appreciate should somebody be kind enough to offer me a solution.



I have a class named Person and a subclass of this named Worker. In the main method I am defining an array as:



Person myPersons[] = new Person[N];



that is an array of objects of class Person. Some of the objects inside this array extend to the class Worker. In class worker I have a very simple method getwGroup() that reads and returns a particular value from within the array that belongs to the class Worker. I am trying to access this method from a method inside the main method as follows:



wgroup = ancestPerson.getwGroup();
where ancestPerson is of type Person and is defines in the main method as:



Person ancestPerson;


ancestPerson = new Worker (...parameters list...wGroup,...parameters list...);


where parameters list are the other items, I am trying to get the value of wGroup.



I hope I have been clear and given enough information so someone can help me. I am still very new to OOP and Java so please accepts my apologies.



Thanks.



Mark





Please use html tags to format code blocks.

   <<Less

Re: Calling methods in subclass from main method

Posted By:   Joe_Morse  
Posted On:   Tuesday, March 19, 2002 10:54 AM

I take it you're iterating through the Person[] array and trying to find out if each instance is a Worker? To do that try using the instanceof operator:

Person[] array = ...
...
for (int i = 0 ; i < array.length; ++i) {
if (array[i] instanceof Worker) {
wgroup = ((Worker)array[i]).getwGroup();
}
}


The instanceof operator tells you if a particular Object is of a particular type. If that instance is indeed a Worker object, you can then cast it and call the method.
About | Sitemap | Contact