Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 4 Methods class

Slide 3

Slide 3 text

Constructors

Slide 4

Slide 4 text

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.

Slide 5

Slide 5 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 7 Example

Slide 6

Slide 6 text

Getters and Setters

Slide 7

Slide 7 text

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.

Slide 8

Slide 8 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 10 Example

Slide 9

Slide 9 text

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.