java - Why is this method static? -
i working on app uses this example base. scroll down class called "detailsfragment". see method:
public static detailsfragment newinstance(int index) { detailsfragment f = new detailsfragment(); // supply index input argument. bundle args = new bundle(); args.putint("index", index); f.setarguments(args); return f; } why method static ? couldn't done regular constructor this:
public detailsfragment(int index) { bundle args = new bundle(); args.putint("index", index); this.setarguments(args); } and when need object go:
detailsfragment f = new detailsfragment(somevalue); i don't see why method static.
why method static ? couldn't done regular constructor this
basically first approach using static factory method. in case, there might no difference. can write same code in constructor. well, there android specific issue, specified in comments @zapl. if provide own parameterized constructor, compiler won't provide default constructor. specified in comments, every fragment must have default constructor.
but, in general, there several benefits of using static factory method. of them are:
- you can implement singleton pattern static factory method
- a static factory method can return instance of subclass.
the best reference regarding topic can find in effective java book - item 1, i've linked below.
reference:
Comments
Post a Comment