简体   繁体   中英

Java: public static newInstance()

Can someone explain what this piece of code does. For example, what's the second declaration do? ie public static AlertDialogFragment newInstance() here:

public static class AlertDialogFragment extends DialogFragment {

    public static AlertDialogFragment newInstance() {
        return new AlertDialogFragment();
    }

In android when your class extends Fragment it needs to have a no arguments constructor(or have no constructor at all) but if you want to set something to every object of the fragment when you create it you can do follwing:

public static class AlertDialogFragment extends DialogFragment {
    private int value=0;
    public static AlertDialogFragment newInstance(int value) {
        AlertDialogFragment instance=new AlertDialogFragment();
        instance.value=value;
        return instance;
    }
}

Now you get the AlertDialogFragment object by calling:

AlertDialogFragment fragment=AlertDialogFragment.newInstance(10);

In your case newInstance method is not achieving much.

Just creating a new instance of AlertDialogFragment and returning.

Usually we create instnace like

AlertDialogFragment adf = new AlertDialogFragment();

in your case

 AlertDialogFragment adf = AlertDialogFragment.newInstance();

See, no difference.

newInstanse() is a method of java.lang.Class which will create a new instance of the class type specified. It will simply call the default constructor similar to what we do when we call,

 Class instance = new Class();

The docs for it says:

The java.lang.Class.newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

Source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM