I'm quite base in Java because I'm full time C# developer but i need make some private project in Android.
In C# i can do something like this :
public class Test
{
public string A {get;set;}
public OtherClass B {get;set;}
}
public OtherClass ()
{
string Some {get;set;}
string Again {get;set;}
}
Now when I want to use class test i can do code like:
var test = new Test
{
A = "test",
B = new OtherClass
{
Some = "Some",
Again = "Again"
}
};
Thank to this now i have initialized test in clear way.
When i want do this in Java i must make code like :
public class Test
{
private string A;
public string GetA()
{
return A;
}
public void SetA(string a)
{
A = a;
}
privte OtherClass B;
public OtherClass GetB()
{
return B;
}
public void SetB(OtherClass b)
{
B = b;
}
}
public class OtherClass
{
private string Some;
public string GetSome()
{
return Some;
}
public void SetSome(string some)
{
Some = some;
}
privte string Again;
public string GetAgain()
{
return Again;
}
public void SetAgain(string again)
{
Again = again;
}
}
I know that Java must have Seter and Geter to field and i'm ok with this but now if i want to use Test
object in way like i use it in C# i must do something like :
OtherClass otherClass = new OtherClass();
otherClass.SetSome("Some");
otherClass.SetAnothier("Another");
Test test = new Test();
test.SetA("A")
test.SetB(otherClass);
IMO this is not nice and clear declaration. I know that i can add constructor like :
public Test(string a, otherClass b)
{
A = a;
B = b;
}
and
public OtherClass(string some,string another)
{
Some = some;
Another = another;
}
And use it like :
Test test = new Test("Test",new OtherClass("some","Another"));
But when i have more complicated classes ( e.g with 200 field ( yes i have that )) the constructor will be very long and it will hard to read it.
So can I initialize class in Java in other way that this I show you ?
Thank
You can actually use object initializers
in java also, however they are called double brace initializers
. Example:
Test test = new Test()
{{
SetA("test");
SetB(new OtherClass()
{{
SetSome("Some");
SetAgain("Again");
}});
}};
However you should probably not use this since it has some weird/unexpected side effects. This example produces an AnonymousInnerClass
for Test
and OtherClass
. You can read more about double brace initializers here.
If you have more parameters than you wish to pass down your constructor you could use the builder pattern as suggested by this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With