Results 1 to 18 of 18
- 12-07-2010, 04:28 PM #1
Member
- Join Date
- Dec 2010
- Posts
- 6
- Rep Power
- 0
Assign Different Objects to Array
Hello everyone!
I’m new to Java, we just start it in college 3 month ago and I got my 1st assignment
So I have 5 classes
1) “Building” – this is base class (template)
2)3)4) “Office”, “Industrial”, “Residential” – They are inherited from “Building” and have some common attributes and different attributes, the same with methods.
5) Control class – main
The idea is to store classes (2,3,4) in array, access them and modify.
Problem:
If I assign array like this
And save it to array like thisJava Code:Building [] list = new Building [100];
It stores fine and I can display all but I can’t access some methods which are specific to “Office” class because they are not mentioned in “Building”Java Code:Office office = new Office{***constructor***}; List[pos]=office;
Ok, it is logical and I understand it
Now I have question:
Is there any way to define some abstract array of objects not depending on the any exist class
Where I would be able to store all my 3 different classes and access they’re methods depending on the class?
P.S. I can define 3 arrays for each class
but I believe it is stupid and not right. I don’t need 3 different arrays I need just 1Java Code:Office[] office = new Office[SIZE]; Industrial[] industrial = new Industrial[SIZE]; Residental[] resident = new Residental[SIZE];
Could you please advise me something? Preferably with simple language/explanation cause I’m not so advanced in Java to understand fancy Java jargon
Thank you very much in advance
- 12-07-2010, 04:54 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
Implement the 'visitor' pattern. Your class is the visitor and all the different Building subclasses are the visitees. Your visitor has a Building (not knowing which one exactly) but it knows that every building has a visit(Visitor visitor) method. A visitor itself implements the following interface:
In each and every type of Building the building calls one of the methods in the visitor; e.g. in an Office object this happens;Java Code:public interface Visitor { public void accept(Office office); public void accept(Industiral industrial); public void accept(Residential residential); }
In the Building superclass the method is defined as an abstract method:Java Code:public class Office extends Building { public void visit(Visitor visitor) { visitor.accept(this); } }
So, basically a visitor calls a visitee and the visitee calls back the visitor with the right method. In the visitor it does what it has to do in the three different methods. The visitor pattern is also called the 'double dispatch' pattern for the above reason.Java Code:abstract class Building { abstract public void visit(Visitor visitor); ... }
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-07-2010, 05:10 PM #3
Member
- Join Date
- Sep 2010
- Location
- Oregon, usa
- Posts
- 69
- Rep Power
- 0
Does the Building class need to implement Visitor, or is it just the subclasses of Building?
:cool: It's all here: http://download.oracle.com/javase/6/docs/api/
- 12-07-2010, 05:12 PM #4
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
- 12-07-2010, 05:16 PM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
None of them need to implement the Visitor interface; it's your class that implements it because it wants to visit those Building classes. Of course I could've defined a Visitee interface:
and all the Building classes have to implement it (to be more exact: only the superclass Building needs to implement it but it's abstract so the real implementations go in the subclasses of the Building class).Java Code:public interface Visitee { public void visit(Visitor visitor); }
kind regards,
Jos
edit: too slow again ... ;-)Last edited by JosAH; 12-07-2010 at 05:18 PM.
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-07-2010, 06:11 PM #6
Member
- Join Date
- Sep 2010
- Location
- Oregon, usa
- Posts
- 69
- Rep Power
- 0
Just to be clear, I'm not the original poster; but his/her question is similar to what I'm currently working on and my first thoughts for a solution were Type casting or an ArrayList. Both would need code to determine the objects type first in order to cast it correctly... very tedious and not very flexible!
I'm reading more on about the double-dispatch design pattern and interfaces. :):cool: It's all here: http://download.oracle.com/javase/6/docs/api/
- 12-07-2010, 06:14 PM #7
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-07-2010, 06:34 PM #8
Member
- Join Date
- Dec 2010
- Posts
- 6
- Rep Power
- 0
JosAH Thnak you very much! but it kind of advanced way of programming, we never did "the 'visitor' pattern" in college, so my teacher might suspect that it wasnt me who write the code and i will have to do extra explanation... im not afreid of it, but from other side if teacher want she can reduce my mark on suspecios of other help
anyway I find solution in teacher notes so ill explain it to tashimoto
we have to define base class as abstract class, in my case its like this:
second thing we have to define empty method in this base classJava Code:public abstract class Building{****}
in my case its "calculate rate"
so in Building abstract class i define empty method
so the differents in the motheds in iheireted classes was around calculateRate(); but u are stil able to access trough array cause it was declered in main classJava Code:public abstract int calculateRate();
hovewer if you want still access some specifi methods which are not define in base class
you have to use trick like this:
so as u see i got object from aray to the temp instance of similar objectJava Code:Office office = (Office) list[pos]; office.setOwner_name(name); office.setAddress(address); office.setPhone_nr(phone); office.setM2(m2);//till here its common methods in all classes from base class office.setOffice_size(office_size); //this is specific method, decleared only in // Office clas which inherited from Buildings, but not decleared in Buildings list[pos] = office;
since im in this object i can use specific methids to this object
once it changed copy back to array at same position (replace)
but you have to be sure that instance of object at array[pos] is equal to object u copy to
to find out it use simple check like this
im not so advanced to explain it properly, but i personaly got the point.Java Code:if (list[pos] instanceof Office){***}
if you need help I might place ehere my teacher programs as example, its very clear
P.S. tashimoto im He not she :)
also I tried to do it trough ArrayList(); but its even more complex and worth to go there only in case if you need dinamic array without space limitLast edited by Briksins; 12-07-2010 at 06:37 PM.
- 12-07-2010, 06:58 PM #9
Member
- Join Date
- Sep 2010
- Location
- Oregon, usa
- Posts
- 69
- Rep Power
- 0
Thanks! That is how I am currently coding my work project. And you explained it just fine! :)
I am finding that this way isn't very flexible, though. Say we decided to add an object, Educational that extends Building. Now we have to recode our Controlling class to add the Type casts for all calls to the Educational methods. And even worst, a few months later our client/customer/boss wants us to add yet another Building type of Parking. Uggg, now we have to go back again and recode. :)
Your question was a good one that brings up real world situations! :):cool: It's all here: http://download.oracle.com/javase/6/docs/api/
- 12-07-2010, 07:27 PM #10
Member
- Join Date
- Sep 2010
- Location
- Oregon, usa
- Posts
- 69
- Rep Power
- 0
It's the humbug parts that are confusing! :)
So with your visitor code example above, the class implementing the Visitor interface will have a body for each of the accept methods?? The object Building will call the visit method and pass the implementing class as the parameter??
eg:
I'm going to code it for real and figure it out... If I need to, can I ask you for further explanation in a new thread, Jos??Java Code:public SomeClass implements Visitor { // main method { and ...other code here... Building[] building = new Building[100]; building[0] = new Residential(); building[0].visit(this); // <-----this doesn't seem correct } public void accept(Residential residential) { // Not really sure what would go here } }:cool: It's all here: http://download.oracle.com/javase/6/docs/api/
- 12-07-2010, 07:43 PM #11
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-07-2010, 10:05 PM #12
Member
- Join Date
- Sep 2010
- Location
- Oregon, usa
- Posts
- 69
- Rep Power
- 0
Ok. But I think I misunderstood what the Visitor interface was doing. I thought that it would allow the class to have an array of Buildings filled with different Types of Buildings (Office, Residential, Industrial), and that each of Type's methods could be called without Type casting.
I'm having a hard time seeing it...
If we use Briksins example below (which uses type casting)
How does the Visitor interface allow the class to call the methods that the Building subclasses do not share?:cool: It's all here: http://download.oracle.com/javase/6/docs/api/
- 12-07-2010, 11:59 PM #13
Member
- Join Date
- Dec 2010
- Posts
- 6
- Rep Power
- 0
im not sure I fully understand how to implement this technically
but i believe that from logical point of view this 'visitor' pattern will allow you to access extra methods in extended classes because it fake it in memory like this extra methods assigned to the base class
i mean if u need access extra method in extended class you will call it technically from base class which will re-direct it to extended
so u have your extra access methods trough base class
for example if we have private variable you can access it only inside class
but if you will make it public you will be able to access it from anywhere.
same here, this "visitor" pattern will allow you to access extended methods from base class as they are in same class
brrrrr extremely hard to explain in foreign language :)
- 12-08-2010, 01:42 AM #14
Member
- Join Date
- Sep 2010
- Location
- Oregon, usa
- Posts
- 69
- Rep Power
- 0
Thanks Briksins! I'm still having a hard time understanding the 'visitor' pattern. I think I need to go home and take a break from this and let it all sink into my head! :)
I posted another thread with questions about interfaces here: Interface usage and the double-dispatch pattern
Thanks for letting me ask questions on your post! :)
ChrisLast edited by tashimoto; 12-08-2010 at 01:43 AM. Reason: posted the correct link to the other thread
:cool: It's all here: http://download.oracle.com/javase/6/docs/api/
- 12-08-2010, 07:31 AM #15
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
thanks josAH
but i have a doubt....
what we do if we have to implement more than one method (say 2) in all classes?
which one is apt?
making a pair of methods for each class in a single visitor
or writing two separate visitor for each method?
- 12-08-2010, 07:41 AM #16
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
Ths visitor/visitee pattern is a two step process: the visitor calls the visit( ... ) method on any type of building (it has to be implemented in all type of buildings (see my original reply above). The visitee 'knows' what type of building it is and calls the appropriate method in the visitor again. Now the visitor 'knows' with which type of building it's dealing and can do its dirty deed with that particular type of building; again see my original example: there's an accept( ... ) method in the visitor for each type of building which is called back by the appropriate type of building when it is visited by the visitor.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 12-08-2010, 08:30 AM #17
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
Java Code:package org.java-forums.sample.buildingproject; public interface Visitor { public void accept(Building building); public void accept(Office office); public void accept(Residential residential); }Java Code:package org.java-forums.sample.buildingproject; public abstract class Building { private String address; public Building() { this(""); } public Building(String address) { this.address = address; } abstract public void visit(Visitor visitor); public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }Java Code:package org.java-forums.sample.buildingproject; public class Office extends Building { public Office(String address) { super(address); } @Override public void visit(Visitor visitor) { visitor.accept(this); } public String getWindowWasher() { return "Acme Window Washers, Inc."; } }Java Code:package org.java-forums.sample.buildingproject; public class Residential extends Building { public Residential(String address) { super(address); } @Override public void visit(Visitor visitor) { visitor.accept(this); } public String getNeighborhoodSchool() { return "Millard Fillmore Elementary"; } }Java Code:package org.java-forums.sample.buildingproject; public class Industrial extends Building { public Industrial(String address) { super(address); } @Override public void visit(Visitor visitor) { visitor.accept(this); } }Note that BuildingController does not override accept() for the Industrial type (and doesn't need to).Java Code:package org.java-forums.sample.buildingproject; import java.util.ArrayList; import java.util.List; public class BuildingController implements Visitor { List<Building> buildings = new ArrayList<Building>(); @Override public void accept(Building building) { System.out.println("Address is " + building.getAddress()); } @Override public void accept(Office office) { accept((Building)office); System.out.println("Window washer is " + office.getWindowWasher()); } @Override public void accept(Residential residential) { accept((Building)residential); System.out.println("Neighborhood school is " + residential.getNeighborhoodSchool()); } private void run() { buildings.add(new Office("515 Madison Ave")); buildings.add(new Industrial("4321 Warehouse Way")); buildings.add(new Residential("1313 Mockingbird Ln")); for (Building building : buildings) { building.visit(this); } } public static void main(String[] args) { BuildingController control = new BuildingController(); control.run(); } }
You could also attack this with a bunch of if/else and instanceof but this approach is nice and clean and elegant, I think.
-Gary-
- 12-08-2010, 09:44 AM #18
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
A lot of people think the same, hence the pattern status of the visitor idiom ;-) A disadvantage of this pattern is (as already has been noticed) that if the number of visitee types changes frequently you have to adjust the visitor ever so often, but then again, a blunt if-else-if-else solution has to be changed as well.
b.t.w. omitting the accept( ... ) for the Industrial type only works (and implementing an accept(Building building) method) if the visitor visits a hierarchy of classes. If those classes are unrelated the controller has to implement (at least) an accept(Visitee visitee) method.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
assign a value to two dimensional array
By makpandian in forum New To JavaReplies: 4Last Post: 10-05-2011, 05:21 AM -
Assign objects to classes
By dellacpa in forum New To JavaReplies: 4Last Post: 08-02-2010, 09:27 PM -
Array Assign Values from a Textfile
By fawadafr in forum Java AppletsReplies: 6Last Post: 11-30-2008, 12:10 AM -
Array of Objects
By bluefloyd8 in forum New To JavaReplies: 5Last Post: 01-22-2008, 06:27 PM -
Array with objects
By toby in forum New To JavaReplies: 1Last Post: 07-25-2007, 09:50 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks