CS102 · Annotated SlidesClasses — Classes and Objects
Classes · Annotated slides

Classes and Objects

Classes as blueprints, instance variables and methods, constructors and overloading, information hiding and encapsulation (private + getters/setters), this, static variables and methods, toString, equals, copy constructors and composition (has-a), built up through three versions of a Student class.

Slide text Study notes Highlight: key words Tips, tricks & traps Seen again elsewhere How it can come up

Classes and Objects

CS102
1

Learning Outcomes

•How to declare a class and use it to create an object.

•How to implement a class’s behaviors as methods.

•How to implement a class’s attributes as instance variables and properties.

•How to call an object’s methods to make them perform their tasks.

•What instance variables of a class and local variables of a method are.

•How to use a constructor to initialize an object’s data.

•Encapsulation and data hiding (using private

access specifier and data validation).

•To use keyword this.

•To use static variables and methods.

•To import static members of a class.

2
Exam weight Low

    Class and Method Definitions

    • Java program consists of objects
      • Objects of class types
      • Objects that interact with one another
    • Program objects can represent
      • Objects in real world
      • Abstractions
    3
    Exam weight Low

      Class

      • A class is the definition of a kind of object.
      • It is like a plan or a blueprint for constructing specific objects.
      4
      Exam weight Medium
      1. A class is the blueprint; an object is one instance built from it.
      🎯 How this can come up · 1 question
      MCQ

      A class is best described as:

      Slide 5: Class and Method Definitions
      Exam weight Low
        Slide 6: Class and Method Definitions
        Exam weight Low
          Slide 7: Class and Method Definitions
          Exam weight Low
            Slide 8: Book Reading - Walter Savitch book ch 5 (5.1)
            Exam weight Low
              Slide 9: Class
              Exam weight Low
              1. Attributes (instance variables) hold an object’s state; methods are its behaviour.

              Class Student

              • Attributes:
                • firstName;
                • lastName;
                • phone;
                • gpa;
                • address;
              • Methods
                • PrintGPA
                • PrintInfo
              10
              Exam weight Low

                Class and Instance Variables

                • Note class has
                  • pieces of data (instance variables)
                  • behaviors
                • Each instance of this type has its own copies of the data items
                11
                Exam weight Low

                  Constructor

                  •A constructor: it is a method that:

                  •does not have any return type •has the same name of the class •must be

                  public

                  •Java defines for you a default constructor that initialized all your attributes to null or default values.

                  When you define a constructor with parameters, the default constructor will no longer be available.

                  It is overridden. You must then define your own default constructor.

                  • Example of default constructor for Student class: public Student{

                  }

                  12
                  Exam weight High
                  1. Constructor: same name as the class, NO return type (not even void), runs when you call new.
                  Exam trapWriting a return type (even void) makes it an ordinary method, not a constructor.
                  🎯 How this can come up · 1 question
                  MCQ

                  Which is true of a constructor?

                  Defining Constructors

                  • A special method called when instance of an object created with new
                    • Create objects
                    • Initialize values of instance variables
                  • Can have parameters
                    • To specify initial values if desired
                  • May have multiple definitions
                    • Each with different numbers or types of parameters
                  13
                  Exam weight Low
                  1. If you write no constructor, Java supplies a no-argument default constructor.

                  Constructors

                  • Constructor overloading: means having several constructors inside the same class.
                  14
                  Exam weight Medium
                  1. Constructor overloading: several constructors with different parameter lists.

                  Information Hiding

                  • Access specifier: determines how to access an attribute or a method. Access specifiers are public by default or private
                  • A good programming practice is to make all attributes as private and restrict their access from external classes. This called data hiding or encapsulation, because data is hidden from external classes.
                  15
                  Exam weight Low
                  1. Make attributes private (data hiding) and expose them through public methods.

                  Information Hiding

                  • Programmer using a class method need not know details of implementation what
                    • Only needs to know the method does
                  • Information hiding:
                    • Designing a method so it can be used without knowing details
                  • Also referred to as abstraction
                  • Method design should separate what from how
                  16
                  Exam weight Low

                    The and Modifiers

                    public

                    private

                    public

                    • Type specified as
                      • Any other class can directly access that object by name public
                    • Classes generally specified as public
                    • Instance variables usually not private
                      • Instead specify as
                    17
                    Exam weight Low

                      Data hiding and data Validation

                      • Why data hiding is a good programming practice? data validation
                        • this is needed to perform , i.e. ,make sure that values assigned to attributes are valid
                        • does not allow external program to put non valid values.
                      • How to access (read/write) the attributes? private
                        • use methods to read an attribute value get
                        • use the methods to modify the value of the attribute set
                      18
                      Exam weight High
                      1. Data hiding lets setters VALIDATE values (e.g., reject a negative age).
                      🎯 How this can come up · 1 question
                      Written

                      Why should instance variables be private?

                      Encapsulation

                      • Consider example of driving a car
                        • We see and use break pedal, accelerator pedal, steering wheel – know what they do
                        • We do not see mechanical details of how they do their jobs
                      19
                      Exam weight Low
                      1. Encapsulation: hide the details, show only the interface (like a car’s pedals).

                      Encapsulation

                      • Preface class definition with comment on how to use class
                      • Declare all instance variables in the class as private.
                      • Provide public accessor methods to retrieve data Provide public methods manipulating data
                        • Such methods could include public mutator methods.
                      • Place a comment before each public method heading that fully specifies how to use method.
                      • Make any helping methods private.
                      • Write comments within class definition to describe implementation details.
                      20
                      Exam weight Medium
                      1. Recipe: private instance variables + public accessors (getters) and mutators (setters).

                      Using object-oriented design (Student class)

                      code Student Version1 Class and Student Test

                      21
                      Exam weight Low

                        this The Keyword

                        • This is a keyword in Java that refers to the object of the same class where it is called.
                        • This keyword can be used to call the constructor of the class.
                        • Referring to instance variables outside the class – must use
                          • Name of an object of the class
                          • Followed by a dot
                          • Name of instance variable
                        • Inside the class,
                          • Use name of variable alone
                          • The object (unnamed) is understood to be there
                        22
                        Exam weight High
                        1. this = the current object. Use it when a parameter has the same name as a field: this.name = name; and to call another constructor: this(...).
                        🎯 How this can come up · 1 question
                        MCQ

                        In a constructor with parameter name, which assigns the field?

                        this The Keyword

                        • Inside the class the unnamed object can be referred to with the name this
                        • Example this.name = keyboard.nextLine; this
                        • The keyword stands for the receiving object this
                        • We will seem some situations later that require the
                        23
                        Exam weight Low

                          Static keyword

                          • static keyword: creates a shared attribute or method for all created objects, i.e. class-wide attribute or method.
                          • The keyword final is used to create constant values, .i.e cannot be changed.
                          24
                          Exam weight Low
                          1. static = one shared copy for the whole class; final = constant.

                          Static Variables

                          • Static variables are shared by all objects of a class static final
                            • Variables declared are considered constants – value cannot be changed
                          • Variables declared static (without final) can be changed
                            • Only one instance of the variable exists
                            • It can be accessed by all instances of the class
                          25
                          Exam weight High
                          1. A static variable (e.g., count of Students) is shared by all objects; static final = constant.
                          🎯 How this can come up · 1 question
                          MCQ

                          A counter of how many Student objects have been created should be:

                          Static Variables

                          • Static variables also called class variables instance variables
                            • Contrast with
                          • Both static variables and instance variables are sometimes called fields or data members
                          26
                          Exam weight Low

                            Static Methods

                            • Some methods may have no relation to any type of object
                            • Example
                              • Compute max of two integers
                              • Convert character from upper- to lower case
                            • Static method declared in a class
                              • Can be invoked without using an object
                              • Instead use the class name
                            27
                            Exam weight High
                            1. Static methods belong to the class, not an object (Math.max). They can’t use this or instance variables directly.
                            🎯 How this can come up · 1 question
                            True / False

                            A static method can directly access instance variables.

                            Programming Example- version 2

                            • Write another version of class Student that has a firstName, lastName, id, mobilePhone and a count. Declare the count as a static variable. The count is incremented every time an object of this class is created. Write the default constructor, a constructor that takes parameters: firstName, lastName, id and mobilePhone. Write a third constructor that takes only firstName and lastName. Write the set and get methods for your attributes. Make sure that the phone number consists of 10 numbers and that the first name and last name consist of more than 2 characters. Create a function that displays all the student information and another that displays only the name.
                            • Then write a demo program that tests the methods of your Student class.
                            28
                            Exam weight Low

                              Student Class Code

                              • Student Version 2
                              29
                              Exam weight Low

                                toString Method

                                • toString method is a special method that provides a String representation for any object in Java. By default, it returns a reference to the object but, you can override (changing its definition) it to return another

                                string representation of the object.

                                30
                                Exam weight Medium
                                1. toString() returns a String describing the object; println(obj) calls it automatically.

                                equals method

                                • public boolean equals(Object obj)
                                • the public boolean equals(Object obj) of the Object class compares object references (i.e. addresses) for equality: For any non-null reference values x and y, the call: x.equals(y) to the equals method of the Object class returns true if and only if, x and y refer to the same object, i.e., if x == y has the value true. It is recommended to override the equals method in our class to compare objects based on one or more instance variables.
                                31
                                Exam weight High
                                1. Object.equals compares REFERENCES; override it to compare contents (e.g., same ID).
                                Exam trap== on objects compares addresses; equals (if overridden) compares contents.

                                equals method

                                // Two student objects are equal if theirIDs are equal public boolean equals(Student other){

                                return(this.id == other.getId);

                                } You can test in Main by creating two objects st1 and st2 if (st1.equals(st2)) System.out.println("Equal IDs"); else System.out.println("Not Equal IDs");

                                32
                                Exam weight Low

                                  Copy Constructors

                                  • A copy constructor is a constructor with a single argument of the same type as the class. The copy constructor should create an object that is a separate object but with the instance variables set so that the object is an exact copy of the argument object.
                                  33
                                  Exam weight Low
                                  1. Copy constructor: Student(Student s) builds a separate object with the same values.

                                  Copy Constructors

                                  public Student (Student s){ firstName=s.firstName; lastName=s.lastName; id=s.id; mobilePhone=s.mobilePhone; }

                                  34
                                  Exam weight Low
                                    Slide 35: Static Methods
                                    Exam weight Low
                                      Slide 36: Slide 36
                                      Exam weight Low
                                        Slide 37: Slide 37
                                        Exam weight Low

                                          Composition

                                          • Composition is the has-a relationship between two classes. We say that a class is composed of an object of another class or a class has-a object of another class. For example, the class Student has an object of the class Date.
                                          38
                                          Exam weight High
                                          1. Composition = has-a: a class holds an object of another class (Student has a Date).
                                          Memory trickis-a → inheritance; has-a → composition.
                                          🎯 How this can come up · 1 question
                                          MCQ

                                          A Student class with a Date birthDate field is an example of:

                                          Student Version 3

                                          • Modify your student class to include a date object that represents the birth date of the students in addition to all the previous attributes.
                                          • A Date object is characterized by its day, month and year.
                                          • The date class should have a constructor, set and get methods for all its attributes. In addition the class should include a method to display Date.
                                          • Note that you can write a simple version of class date without validation the attributes.
                                          • Write also a demo program to test your classes.
                                          39
                                          Exam weight Low

                                            • Code of Student Version 3
                                            40
                                            Exam weight Low