Java :Setter Getter and constructor

2019-02-02 06:56发布

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

    public class ExampleClass {

        private int value = 0; 

        public ExampleClass () {
            value = 0; 
        }

        public ExampleClass (int i) {
            this.value = i;
        }

        public int getValue() {
            return value; 
        }

        public void setValue(int val) {
            this.value = val; 
        }

        public static void main(String[] args) {     
            ExampleClass example = new ExampleClass (20);
            example.setValue(20); 
            //Both lines above do same thing - why use constructor? 
            System.out.println(example.getvalue());
        }
   }

All I've learned is that we need getters/setters for security and that they can also be used to change or edit values later on.

My question is that if the constructor is the point of initialization and a default constructor is always present, why use a constructor with parameters to initialize values instead of getters/setters?. Wouldn't using the getter and setter provide security as well being able to easily change values at any stage. Please clarify this point for me.

10条回答
2楼-- · 2019-02-02 07:25

First, both methods: Constructor and Setter are safe ways to change object's attributes. Are expected from Class author to expose or not safe ways to modify an instance.

  1. The default constructor is always provided if you have not written one:

    // Example of a Class with a Default Constructor 
    public class GetSet {
    
        private String value;
    
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    
    
        public static void main(String[] args) {
            // Theres a implicit Default Constructor here
            // Its ok to do that
            // GetSet obj = new GetSet();
            GetSet obj = new GetSet();
        }
    
    }
    
    
    // Example of a Class without a Default Constructor 
    public class GetSet2 {
    
        public GetSet2(String value) {
            this.value = value;
        }
    
        private String value;
    
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    
        public static void main(String[] args) {
            // GetSet2 obj = new GetSet2(); // compile time error
            // Default constructor is not provided, since u wrote one
        }
    
    }
    


2. About which is better: Using a constructor or via setter, it depends on what u want. If you will only modify an attribute of a existing object, u may use the setter, or for a completely filled object you may prefer the constructor instead.

    // Example of modifing an obj via Setter and Constructor
    public class GetSet3 {

        public GetSet3(String value1, String value2, String value3, String value4) {
            this.value1 = value1;
            this.value2 = value2;
            this.value3 = value3;
            this.value4 = value4;
        }

        private String value1;
        private String value2;
        private String value3;
        private String value4;


        // ... Getters and Setters



        public static void main(String[] args) {

            // Its easier to this
            GetSet3 obj;

            obj= new GetSet3("j", "a", "v", "a");

            // instead that
            // its also easy to forget or do something wrong
            // when u have a lot of attributes to set
            obj.setValue1("j");
            obj.setValue2("a");
            obj.setValue3("v");
            obj.setValue4("a");

        }
    }
查看更多
萌系小妹纸
3楼-- · 2019-02-02 07:28

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?

查看更多
小情绪 Triste *
4楼-- · 2019-02-02 07:29

default constructor is always there

Well actually its not always there. A default constructor is the one which is provided by the compiler (of course it is a no-arg constructor ) Only if there is no other constructor defined in the class

why we use constructor with parameters to initialize values instead of set get

Because there could be a condition that an object can always be created only when all the values are provided at the time of initialization itself and there is no default value. So all values must be provided otherwise code will not compile.

Consider this Book class

public class Book {

    private String title;
    private String author;

    public Book(String title, String author){
        this.title = title;
        this.author = author;
    }
     //getters and setters here 
}

Consider a condition where a book can be created only if it has title and author.

  • You cannot do new Book() because no-arg constructor is absent and compiler will not provide one because one constructor is already defined.
  • Also you cannot do new Book() because our condition does not meet as every book requires a title and author.

This is the condition where parameterized constructor is useful.

查看更多
戒情不戒烟
5楼-- · 2019-02-02 07:32

It's easier and safer to initialize your object variables via your constructor to avoid nullpointers.

If you instantiate your object without initializing your variables first and you do a get operation on one of your null variables, you might get a nullpointer exception at runtime because you forgot to manually set its value.

On the flipside of that, if you always initialize your object variables in your default constructor, you have a seriously reduced risk of getting nullpointer exceptions during runtime because none of your variables can be null unless you specifically set them via a setter (which is not recommended).

查看更多
登录 后发表回答