0

What is a constructor, and getter and setter

best way to do a constructor and getters and setters

22nd May 2017, 11:04 PM
Selorm Peterson Adjabeng
Selorm Peterson Adjabeng - avatar
1 Answer
+ 8
A constructor is a method that is called when an object is instantiated. All classes have constructors, if you do not manually create one the compiler will supply an empty (default) one for you. The constructor allows us to initialize members of an object when the object is created. Example: class Animal{ private String name; // constructor Animal(String newName){ name = newName; } } Then if I create an object, I can assign a value to the String name. Animal Dog = new Animal("Doggy"); Here the constructor is called with Doggy as the newName string. Now, what are getters and setters? A getter is something we use to grab the value of a member of the object. Remember the String name is private, so it cannot be accessed from another class. To access it we use a getter. public String getName(){ return this.name; // returns the string name } Then we can call this to get the name of the object: String dogName = Dog.getName(); // dogName = "Doggy" A setter will allow us to change the value of the member. public void setName(String newName){ this.name = newName; // set new value of String name } Now we can change name using this setter at any time we please. Dog.setName("myNewDoggy"); Now the String name equals to myNewDoggy instead of Doggy. Getters and setters are also called accessers and mutators. (Means the same thing). So why not make the members public instead of private? Short answer since I'm lazy: Encapuslation, and data-hiding. It also makes De-bugging far easier! Long answer: https://softwareengineering.stackexchange.com/questions/143736/why-do-we-need-private-variables
22nd May 2017, 11:20 PM
Rrestoring faith
Rrestoring faith - avatar