Why have getInstance methods?

Can anyone please explain what is the purpose of a getInstance method.
If a class is abstract and cannot be instantiated why does the class allow you to make an instance of it by using a getInstance method. I find this concept very confusing.
Cheers

To control instantiation. E.g. for singletons, or factories, or like this
public class RestrictedValue {
  private RestrictedValue(int i) { // can't be called by anybody else
  static RestrictedValue getInstance(int value) {
    if (value > 0 && value < 128) {
      return new RestrictedValue(value);
    } else {
      return null;
}Not the nicest code, but you get the idea.

Similar Messages

  • Why have static methods?

    What is the criterion to decide whether a method should be static or not?

    lets say you have a class called Utility. No other class ever needs an instance of Utility becuase all of it's methods are static and the class is public. Example:
    package com.abc.util;
    /* make it final so can't extend */
    public final class Utility
       /* can't call new Utility now */
       private Utility()
       /* these methods below, by just seeing their names, should be static */
       public static long ipStringtoLong(String address){}
       public static String execShellCMD(String shellCMD){}
       // ect ...
    }Now a class can import and use it. There are no instances associated with these methods except the values passed to them. It makes them accessable from anywhere in your application w/o worrying about having a ref to an Object. Their accessable as long as the class can be found in your class path. Jar'em up and put them into C:\jdk1.xx\jre\lib\ext\util.jar
    import com.abc.util.Utility;
    // ........(String host, String port){
       long ipLong = Utility.ipStringToLong(host);

  • Why does not JButton have processActionEvent method, unlike Button ?

    java.awt.Button has processActionEvent( ActionEvent e) method which ( as i think ) calls actionPerformed(e) of the registered listeners.
    Why does not javax.swing.JButton have this method ? from where and how is actionPerformed() of JButton called ?
    I want to know how exactly this event is handled ?
    Thanks in advance.

    eng.robo wrote:
    java.awt.Button has processActionEvent( ActionEvent e) method which ( as i think ) calls actionPerformed(e) of the registered listeners.
    Why does not javax.swing.JButton have this method ? from where and how is actionPerformed() of JButton called ?Swing and AWT are very different and you should not expect one to have the methods of the other.
    I want to know how exactly this event is handled ?Have you read the JButton section in the Sun Swing tutorial? This will tell you much. To see exactly how actions are handled in JButtons, I suggest that you open and look through the source code for the AbstractButton and DefaultButtonModel classes.

  • Why Set does not have get() method

    Can some one tell me why set does not have get method?...

    user12203354 wrote:
    ya u are right that designer of this class thought there is no implementation required for get but why he/she thought like this...
    there must be some valid reason for the same.Because a Set's purpose is not to keep things in order; it's to ensure there are no duplicate entries. Set would require extra code to be able to keep track of an order.
    Note that there is a Set implementation that does keep track of insertion order--LinkedHashSet--but it doesn't have a get() method.

  • Why is it that the interfaces cannot have static methods?

    why is it that the interfaces cannot have static methods?

    Interfaces contain polymorphic methods. Static methods are not polymorphic, and therefore would not make any sense to be in interfaces.

  • Why IVisualElementContainer does not have "getChildren" method defined?

    Hi all,
    In Flex 3 SDK Container.as has method getChildren() and rawChildren property typed as IChildList.
    But In Flex 4 the interface IVisualElementContainer does not have a definition for getChildren() > thus neither SkinnableContainer nor Group have this method defined.
    Was this decision made deliberately to simplify the interface API?
    I find it convenient to have "getChildren" method implemented inside Group and SkinnableContainer,  for example this can be useful if I want to access all visual childs of those containers to pass them along to some manager class or to dynamically set some common property of all childs ( e.g visibility).

    MX had a concept of two sets of children: regular children and raw children.  One component could have two children lists.
    Spark simplifies this concept because of the skin.  Now there's really only one set of children.  Because of this IVisualElementContainer acts like IChildList and has a very similar API.  You should be able to use IVisualElementContainer as you would IChildList before.
    Note that in places where we do have more than one-set of children, we don't expose them on the main object, but require you to dig down in to the separate object (the skin or the controlBarGroup for example).
    Hope that helps,
    Ryan

  • Properties does have getProperty method

    I have this code but the Properties does have the method getProperty()
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class TestCode {
        static final String PROPERTY_FILE="JDBC-ODBC Driver.properties";
        String driverName, url, user, password;
        /** Creates a new instance of TestCode */
        public void access() {
            try{
                /* Create an object of the Properties class and load properties. */
                Properties prop=new Properties();
                prop.load(new FileInputStream(PROPERTY_FILE));           
                driverName=prop.getProperty("driver");  // Retrieve driver information.           
                url=prop.getProperty("url");    // Retrieve JDBC URL.
                user=prop.getProperty("user");  // Retrieve user name.
                password=prop.getProperty("password");  // Retrieve password.
                /* Initialize and load a driver. */           
                Class.forName("driverName");
                /* Establish a connection with a database. */
                Connection con=DriverManager.getConnection(url,user,password);
                /* Create Statement object. */
                Statement stmt=con.createStatement();
                /* Executes a SQL query to retrieve a ResultSet. */
                ResultSet rs=stmt.executeQuery("SELECT * FROM Registered_Users_Information");
                /* Iterate through the ResultSet to display data. */
                while(rs.next()){
                    System.out.println(rs.getString("UserName"));
                    System.out.println(rs.getString("Password"));
                con.close();
            }catch(Exception ex){
                ex.printStackTrace();
        public static void main(String args[]){
            TestCode t=new TestCode();
            t.access();
    }Please show me the problem.
    Thanks.
    Nguyen_Tom

    I used this code but it does not exist. Has anyone
    tell me why or please five me an advise? The object
    prop does not has the method load.
    Properties prop=new Properties();
    prop.load(new FileInputStream(PROPERTY_FILE));Thanks a lot.
    Nguyen_TomRefer to the JDK spec since 1.0, Properties should have all the methods you said you didn't have.
    Did your program throw any error messages?? Could you show me?
    :D

  • Singleton Class using a constructor not a getInstance method

    Hi,
    I have a class with a couple of contructors, the class is instantiated many times in the application.
    Is there any way by which I can return a single instance of the class when the contructor is called ?.
    I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
    This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
    Example
    XXXClass xxx = new XXXClass();
    every time new XXXClass() is called the single instance of the class must be returned.
    I dont want to implement
    XXXClass xxx = XXXClass.getInstance();
    Thanks in advance
    Rgds
    Pradeep Thomas

    The short answer to your question is No. If your class has accessible constructors and your code calls "new" then there will be multiple instances of the corresponding objects.
    Possible ways round your problem are to use static variables in place of instance variables or to use your existing class as a wrapper for another class that is instantiated only once. This second class should include all the variables and methods and the wrapper class would delegate all calls to it. This is not quite a singleton because there would still be multiple instances of the wrapper, but each instance would share the same variables and methods. You could also add a getInstance() method to the wrapper class so that new code could start to use it as a singleton.
    Other than that, it's time to refactor! Good Luck.

  • Working of serializable interface, when it doesn't have any methods

    Hi,
    I am curious about how the serializable interface is used in JVM.
    This is an empty interface. ie. it does not have any method signatures or any variables inside.
    How does java use this interface, for serializing purposes.
    Also, why should it be an interface, when its all empty.

    Such marker interfaces are just used to tell something about about a class, in this cases that the developer wants that instances of a class can be serialized. The code that handles the serialization just check s"instanceof Serializable". Of course Serializbale could look like this
    public interface Serializable
    public boolean isSerializable();
    But why make things more complicated than necessary?

  • Why are interface methods public?

    I want to define a package interface that will be implemented only by package classes which will be used only by other package classes. Why do the methods have to be public?

    In java you don't have multiple inheritance. To
    circumvent that it is said to extend the most
    important class and implement the others with
    interfaces. No. Java does not support multiple inheritance. Interfaces do not exist to supply that functionality. Interfaces can be used to simulate some of the patterns that multiple inheritence represents.
    (You can have skeleton implementations to
    help you implement those interfaces in other
    classes).
    But the interface methods are public. So all the
    classes you 'extend' via this trick have all methods
    public.
    This is a bad thing. All of you who have used RMI (or
    J2EE) know that you can serialize objects between two
    networked machines. ValueObjects pattern from J2EE
    toolbox is a good example of this. Now, if you happen
    to have several quite similar objects, you obviously
    would like them to inherit those common traits from
    some base class. If you would also like them to have
    some other common functionality (for example server
    side 'maintenance' methods, state monitoring, checking
    and clearing, you would have to make those methods
    public 'cos you only have interface implementation
    left - after spending that single credit to actual
    inheritance.No. Convienence ("common functionality") should not be used in most cases when designing hierarchies. Inheritence should only be used to represent 'is a' relationships.

  • Why have all the music I have in my WAV folder been transferred to my ITunes Library? I DO NOT want them there,

    Why have all the music I have in my WAV folder been transferred to my ITunes Library? I DO NOT want them there, They (WAVs) are strictly used for EMail.
    wavs

    You might still be able to recover them using one of the methods discussed in this older thread, but many of them require a full functional, noncorrupted iPod filesystem in order to work properly. 
    https://discussions.apple.com/thread/2452022?start=0&tstart=0
    B-rock

  • Why have MPEG2 and DVD presets

    i have a 3 min project i am pressing for DVD,
    what is the difference between the compressor presets for MPEG 2 and DVD?
    they are both MPEG2! I only had MPEG2 until i upgraded to FC Studio.
    the only diff i can find is 1 can be 60mins and the other does 90mins.
    so why have the 2 lists containing 20 options when most are the same?
    Also I shot it with a Z1P in DV wide and worked in FCP in anamorpic and have tried compressing in 16:9 and building the dvd in DVDSP in 16:9 but the final burned DVD plays on my Widescreen LCD TV in a wide version but it is letterboxed and streched horizontally a bit
    cheers
    TH

    If you simply appled the FC Studio upgrade over an existing installation which inclided Compressor 1.2.1, the old presets were not removed.
    All the Standard Definition presets in Compressor 2.0 are prefixed by "DVD".
    All the old presets are prefixed with "MPEG-2".
    Do not use the old presets with Compressor 2.0
    Delete the old presets which can be found in User/Library/Application Support/Compressor/
    There is a more elegant method which I believe is accomplisehed by moving that "Compressor" folder to the desktop and restarting Compressor 2.0
    A new folder with the correct presets will be built.
    But I haven't done this myself, nor did I have to as I wiped my drive before installing FC Studio.

  • Calendar.getInstance method not loading userdefined locale classes

    Hi
    In JDK 6
    I have implemented CalendarData_en_AT class for locale(en, AT) which is a user defined locale(not defined in jre). I see that when I try to load the locale using Calendar.getInstance method it loads CalendarData_en.class
    When further debugged, I found that it picks up only the locales that are specified in LocaleMetaDataInfo class
    What needs to be done so that when we call Calendar.getInstance(new Locale(en, AT)) it loads CalendarData_en_AT.class
    Thanks
    -Beena

    I have a class CalendarData_en_AT.java
    public class CalendarData_en_AT extends LocaleNamesBundle
    public CalendarData_en_AT()
    protected final Object[][] getContents()
    return (new Object[][] {
    new Object[] {
    "firstDayOfWeek", "2"
    }, new Object[] {
    "minimalDaysInFirstWeek", "4"
    The compiled class is enclosed in a .jar file and have been placed in jre/lib/ext
    Now from my test class
    if I call Calendar.getInstance(new Locale("en","AT")).getFirstDayOfWeek()
    it should return 2, but as of now it returns 1, reason being it loads CalendarData_en.class and not CalendarData_en_AT.class which is user implemented

  • In CC214 PS Why has adobe removed the "print Size Button"  And why have they made the Brush preview window so small you can't see the effects to accurately adjust them?

    In CC214 PS Why has adobe removed the "print Size Button"  And why have they made the Brush preview window so small you can't see the effects to accurately adjust them?
    These two things need to be remedied in their upgrades because It's become such a bother I've had to revert to older versions of PS.

    Yea, and it's a pain to get to.  What was the rational for removing the print size button?   With the magnifying glass tool selected in older versions of Photoshop you would get a button that says "print size" right next to Actual pixels, Fit Screen, Fill Screen. Now I have to go out of my way and dig for it if I want to see the print size.  Of all the buttons you could have taken away, why not fill screen?  I never use that.
    Besides the point I just downloaded the Oct Upgrade for PS and surprise! Nothing has changed and these are two big black eyes on newer versions of Photoshop.   The Brush preview window is  unchanged in CC but in CC2014 it's basically worthless.  If you apply a texture to a brush you can't properly see the scale of the texture, the spacing, scatter, etc...

  • Why have apple made such a great item in the ipad2, and then just ruined it by air print, I have a Kodak wireless, and I am not paying stupid ink prices, the cost of air printers is huge, and the ink worse, why have they ruined a good item.

    AirPrint,,,, WHy?      Why have apple robbed us yet again, AirPrint, is useless, or buy another printer that apple have gained massive revenue from, the iPads are great but very high priced, and then you have to buy another high priced printer with high priced inks, I use a wifi Kodak, why should I buy another.
    You have to mess about with other apps and then have your other computer on, what's all that about Apple. Why have they ruined a really good thing.
    I cannot get my printer to work, and might just sell this stupid gadget, I am so annoyed at apple playing god with things, if you want it to work you have to jailbreak it, and the up pos Apple again, if you break it we will not repair it, that tells you exactly that they are playing god, wake up apple and smell the coffee.

    I have a Kodak wifi printer and print using the app Print Magic.  I do not need to have any of my home computers on to do this as they have nothing to do with wifi printing from my iOS devices (if you do not have a wifi printer and are sharing the printer off another computer, then of course, that computer needs to be on and connected to your wifi network).
    You can post with all the hyperbole you want, but none of us have any inside information as to why Apple's devices and iOS do certain things a certain way, or why they do not do things in the particular specific way you wish them to.  Airprint does not work with Kodak printers at this time.  There are numerous apps that will allow you to print to just about any wifi printer.

Maybe you are looking for