Java initializes a class in style, as in C #

I'm quite thorough in Java because I'm a full-time C # developer, but I need to do some kind of private Android project.

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 that I want to use a class test, I can make code like:

var test = new Test
{
    A = "test",
    B = new OtherClass
    {
        Some = "Some",
        Again = "Again"
    }
};

Thanks to this, I now initialized the test in a clear way.

When I want to do this in Java, I have to 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 should have Seter and Geter in the field, and I'm fine with that, but now, if I want to use the object the Testway I use it in C #, I should do something like:

OtherClass otherClass = new OtherClass();
otherClass.SetSome("Some");
otherClass.SetAnothier("Another");
Test test = new Test();
test.SetA("A")
test.SetB(otherClass);

IMO is a bad and clear declaration. I know that I can add a 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"));

(, 200 (, )), , .

, Java , ?

+4
1

object initializers java, double brace initializers. :

Test test = new Test()
{{
    SetA("test");
    SetB(new OtherClass()
    {{
        SetSome("Some");
        SetAgain("Again");
    }});
}};

, , , / . AnonymousInnerClass Test OtherClass. .

, , , .

+8

Source: https://habr.com/ru/post/1627413/


All Articles