erik
erik

Reputation: 4948

constructor with non essential vars

I was wondering if it is possible and if so how, to create a constructor that takes three variables but will not through an error if the last two are not passed?

something like:

public void onCreate(Bundle savedInstanceState, String s1<non essential>) 
    {

Upvotes: 2

Views: 113

Answers (3)

emory
emory

Reputation: 10891

I really like dash1e's answer best. Luis Miguel Serrano has some excellent additional suggestions.

In addition - if appropriate - you can use varargs

public MyCreate(Bundle savedInstanceState, String ... args) 

which has the same effect as

public MyCreate(Bundle savedInstanceState, String [ ] args ) 

it is very similar to Luis Miguel Serrano of using a List but you don't have to go to the hassle of creating a List.

Upvotes: 0

dash1e
dash1e

Reputation: 7807

Create more contructors

public MyCreate(Bundle savedInstanceState) 
    {

public MyCreate(Bundle savedInstanceState, String s1) 
    {

public MyCreate(Bundle savedInstanceState, String s1, String s2) 
    {

try to read this article on constructor overloading.

Upvotes: 12

Luis Miguel Serrano
Luis Miguel Serrano

Reputation: 5099

You have multiple ways of doing this. To name a few:

  • You can have multiple constructors with different signatures (as
    suggested by dash1e)
  • You can have List of the type of variables you want (or of
    Objects, in case you want it to be fully generic), and have a
    constructor which takes the list and uses its values when present.
  • You can have a custom data model class to encapsulate the three
    types of values you want to deal with and use it in constructor
    ,
    making it so that when its values are being fetched by the
    constructor of your class, they are optional for the arguments you want.

Upvotes: 0

Related Questions