Results 1 to 18 of 18
  1. #1
    Briksins is offline Member
    Join Date
    Dec 2010
    Posts
    6
    Rep Power
    0

    Default 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
    Java Code:
    Building [] list = new Building [100];
    And save it to array like this
    Java Code:
    Office office = new Office{***constructor***};
    List[pos]=office;
    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”
    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
    Java Code:
    Office[] office = new Office[SIZE];
    Industrial[] industrial = new Industrial[SIZE];
    Residental[] resident = new Residental[SIZE];
    but I believe it is stupid and not right. I don’t need 3 different arrays I need just 1

    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

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    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:

    Java Code:
    public interface Visitor {
       public void accept(Office office);
       public void accept(Industiral industrial);
       public void accept(Residential residential);
    }
    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 class Office extends Building {
       public void visit(Visitor visitor) {
          visitor.accept(this);
       }
    }
    In the Building superclass the method is defined as an abstract method:

    Java Code:
    abstract class Building {
       abstract public void visit(Visitor visitor);
       ...
    }
    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.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    tashimoto is offline Member
    Join Date
    Sep 2010
    Location
    Oregon, usa
    Posts
    69
    Rep Power
    0

    Default

    Does the Building class need to implement Visitor, or is it just the subclasses of Building?

  4. #4
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by tashimoto View Post
    Does the Building class need to implement Visitor, or is it just the subclasses of Building?
    Your Control class implements Visitor.

    -Gary-

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by tashimoto View Post
    Does the Building class need to implement Visitor, or is it just the subclasses of Building?
    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:

    Java Code:
    public interface Visitee {
       public void visit(Visitor visitor);
    }
    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).

    kind regards,

    Jos

    edit: too slow again ... ;-)
    Last edited by JosAH; 12-07-2010 at 05:18 PM.
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    tashimoto is offline Member
    Join Date
    Sep 2010
    Location
    Oregon, usa
    Posts
    69
    Rep Power
    0

    Default

    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. :)

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by tashimoto View Post
    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. :)
    If you use the visitor pattern the visitees are called by the visitor and they call it back (hence the 'double dispatch') with the correct method according to their actual type. It's easy when you understand all the humbug.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  8. #8
    Briksins is offline Member
    Join Date
    Dec 2010
    Posts
    6
    Rep Power
    0

    Default

    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:
    Java Code:
    public abstract class Building{****}
    second thing we have to define empty method in this base class
    in my case its "calculate rate"
    so in Building abstract class i define empty method
    Java Code:
    public abstract int calculateRate();
    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 class
    hovewer if you want still access some specifi methods which are not define in base class
    you have to use trick like this:
    Java 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;
    so as u see i got object from aray to the temp instance of similar object
    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
    Java Code:
    if (list[pos] instanceof Office){***}
    im not so advanced to explain it properly, but i personaly got the point.
    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 limit
    Last edited by Briksins; 12-07-2010 at 06:37 PM.

  9. #9
    tashimoto is offline Member
    Join Date
    Sep 2010
    Location
    Oregon, usa
    Posts
    69
    Rep Power
    0

    Default

    Quote Originally Posted by Briksins View Post
    anyway I find solution in teacher notes so ill explain it to tashimoto ... im not so advanced to explain it properly, but i personaly got the point.
    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! :)

  10. #10
    tashimoto is offline Member
    Join Date
    Sep 2010
    Location
    Oregon, usa
    Posts
    69
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    If you use the visitor pattern the visitees are called by the visitor and they call it back (hence the 'double dispatch') with the correct method according to their actual type. It's easy when you understand all the humbug.

    kind regards,

    Jos
    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:
    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
       } 
    
    }
    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??

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by tashimoto View Post
    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??
    That's fine with me but please do it here in the forums so others have the opportunity to participate too. b.t.w. the visitor pattern doesn't work very well when your class hierarchy changes frequently, e.g. other types of Buildings are added.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  12. #12
    tashimoto is offline Member
    Join Date
    Sep 2010
    Location
    Oregon, usa
    Posts
    69
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    That's fine with me but please do it here in the forums so others have the opportunity to participate too. b.t.w. the visitor pattern doesn't work very well when your class hierarchy changes frequently, e.g. other types of Buildings are added.

    kind regards,

    Jos
    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)

    Quote Originally Posted by Briksins View Post
    if you want still access some specific methods which are not define in base class
    you have to use trick like this:
    Java Code:
    Office office = (Office) list[pos];
    office.setOwner_name(name);
    office.setAddress(address);
    office.setPhone_nr(phone);
    office.setM2(m2);//until here its common methods in all classes from base class
    office.setOffice_size(office_size); //this is specific method, declared only in
      // Office class which inherited from Buildings, but not declared in Buildings
    list[pos] = office;
    How does the Visitor interface allow the class to call the methods that the Building subclasses do not share?

  13. #13
    Briksins is offline Member
    Join Date
    Dec 2010
    Posts
    6
    Rep Power
    0

    Default

    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 :)

  14. #14
    tashimoto is offline Member
    Join Date
    Sep 2010
    Location
    Oregon, usa
    Posts
    69
    Rep Power
    0

    Default

    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! :)
    Chris
    Last edited by tashimoto; 12-08-2010 at 01:43 AM. Reason: posted the correct link to the other thread

  15. #15
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default

    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?

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by tashimoto View Post
    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...
    How does the Visitor interface allow the class to call the methods that the Building subclasses do not share?
    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,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    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);
    	}
    
    }
    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();
    	}
    }
    Note that BuildingController does not override accept() for the Industrial type (and doesn't need to).

    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-

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,371
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by gcalvin View Post
    Note that BuildingController does not override accept() for the Industrial type (and doesn't need to).

    You could also attack this with a bunch of if/else and instanceof but this approach is nice and clean and elegant, I think.
    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,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. assign a value to two dimensional array
    By makpandian in forum New To Java
    Replies: 4
    Last Post: 10-05-2011, 05:21 AM
  2. Assign objects to classes
    By dellacpa in forum New To Java
    Replies: 4
    Last Post: 08-02-2010, 09:27 PM
  3. Array Assign Values from a Textfile
    By fawadafr in forum Java Applets
    Replies: 6
    Last Post: 11-30-2008, 12:10 AM
  4. Array of Objects
    By bluefloyd8 in forum New To Java
    Replies: 5
    Last Post: 01-22-2008, 06:27 PM
  5. Array with objects
    By toby in forum New To Java
    Replies: 1
    Last Post: 07-25-2007, 09:50 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •