Results 1 to 2 of 2

Thread: Static Method

  1. #1
    mikeZet is offline Member
    Join Date
    Mar 2012
    Posts
    3
    Rep Power
    0

    Default Static Method

    Hello,

    I am following a tutorial which is explaining the Factory Design pattern. In one class a Static Method is used rather than Non Static. Why are they using the former in detriment to the later ?

    Code example:
    Java Code:
    public class Factory {
    	
    	public static Device getDevice(String name){
    		
    		if(name.equalsIgnoreCase("mobile"))
    			return new Mobile();
    		
    		if(name.equalsIgnoreCase("laptop"))
    			return new Laptop();
    		
    		else return null;			
    	}
    }
    Demo Class:

    Java Code:
    public class Demo {
    
    	public static void main(String[] args) {
    		
    		Device mob = Factory.getDevice("mobile");	
    		Device lap = Factory.getDevice("laptop");
    	}
    
    }


    What would be the problem if we used a NON STATIC METHOD to create the devices ?

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

    Default Re: Static Method

    If the method weren't static you'd have to instantiate a Factory (new Factory()) before it can instantiate laptops and/or mobiles for you. It doesn't matter much but a static method is a bit more efficient here ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. Replies: 9
    Last Post: 06-10-2011, 12:40 AM
  2. Replies: 7
    Last Post: 09-24-2010, 05:09 AM
  3. Replies: 3
    Last Post: 02-09-2010, 05:22 AM
  4. Replies: 1
    Last Post: 02-10-2009, 10:03 AM
  5. Replies: 1
    Last Post: 08-07-2007, 05:05 AM

Posting Permissions

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