Java :Setter Getter and constructor

Java Student picture Java Student · Jul 30, 2013 · Viewed 79.5k times · Source

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.

Answer

Prasad Kharkar picture Prasad Kharkar · Jul 30, 2013

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.