Java :Setter Getter and constructor

前端 未结 11 1379
陌清茗
陌清茗 2020-12-25 12:31

I\'m a bit confused about the use of getter/setters and constructors (see the below code for an example)

    public class ExampleClass {

        private in         


        
11条回答
  •  余生分开走
    2020-12-25 13:05

    Sometimes, when creating a new object of a class, some values HAVE TO be provided. For an example, when connecting to database and creating Connection class object you have to provide a connection string, so that it knows what are you connecting to. Creating new connection without specyfing target database would be pretty useless, right?

    Also, take a look at this

    Foo foo=new Foo(1,2,3,4,5,6,7);
    

    and this

    Foo foo=new Foo();
    foo.setP1(1);
    foo.setP2(2);
    foo.setP3(3);
    foo.setP4(4);
    foo.setP5(5);
    foo.setP6(6);
    foo.setP7(7);
    

    First one looks better, right?

提交回复
热议问题