$30 off During Our Annual Pro Sale. View Details »

CSE110 Lecture 19

CSE110 Lecture 19

Principles of Programming with Java
constructors, getters and setters
(202006)

Javier Gonzalez-Sanchez
PRO

June 15, 2017
Tweet

More Decks by Javier Gonzalez-Sanchez

Other Decks in Programming

Transcript

  1. 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

    View Slide

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

    View Slide

  3. Constructors

    View Slide

  4. 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.

    View Slide

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

    View Slide

  6. Getters and Setters

    View Slide

  7. 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.

    View Slide

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

    View Slide

  9. 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.

    View Slide