CSE110 Principles of Programming with Java Lecture 19: Methods: constructor, getter, and setter Javier Gonzalez-Sanchez [email protected] javiergs.engineering.asu.edu | javiergs.com Office Hours: By appointment
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 6 Constructor Method • A constructor is a special method that is used to create a new object. • Each class has a default constructor (without parameter) even if a programmer does not define one. • Each constructor has the following properties: • it has the same name as the class it does not have any return type, not even void • it is always called/used with the reserved word “new”. • it typically sets the initial values of instance variables • We can create multiple constructor methods for one class.
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 9 Getters and Setters • Encapsulation is one of the four fundamental OOP concepts. • In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. • To achieve encapsulation in Java: • Declare the variables of a class as private. • Provide public setter and getter methods to modify and view the variables values.
CSE110 - Principles of Programming Javier Gonzalez-Sanchez [email protected] Summer 2020 Disclaimer. These slides can only be used as study material for the class CSE110 at ASU. They cannot be distributed or used for another purpose.