Table of Contents

Classes and Object Oriented Programming (OOP)


Introduction to Classes and OOP

Overview

Terminology

New Java language features


Object-Oriented Programming (OOP) concepts


A class stores the attributes (data) of something

        public class Student {
            public String firstName;
            public String lastName;
            public int    id;
        }

A class is a type

        Student bestInClass;  // This variable references a Student object.
        Student t;            // And here is another

These don't have values yet, but we'll do that in the next section.


Does your problem require classes or simple variables?


Standard practice: One class per file

        // File   : Student.java
        // Purpose: Information about a student

        public class Student {
            public String firstName; // First name
            public String lastName;  // Last name
            public int    id;        // Student id
        }

Class versus object

Use "new" to create a new object

        Student fred;
        fred = new Student();   // Create Student object with new.

"new" and parentheses

Default field values - null, zero, false

Access public fields with dot notation

        Student fred;                 // Declare a variable to hold a Student object.

        //... Create a new Student object for Fred.
        fred = new Student();         // Create a new Student object with default values.
        fred.firstName = "Fred";    // Set values of the fields.
        fred.lastName  = "Schwartz";
        fred.id        = 9950842;

        JOptionPane.showMessageDialog(null, "One student is named: "
             + fred.lastName + ", " + fred.firstName);

A class definition is a template for creating objects

        //  File  : TestStudent.java

        import javax.swing.*;

        public class TestStudent {
            public static void main(String[] args) {
                Student fred;
                Student pupil;

                //... Create new Student object with new.
                fred = new Student();
                fred.firstName = "Fred";
                fred.lastName  = "Schwartz";
                fred.id        = 9950842;

                //... Create another Student object.
                pupil = new Student();
                pupil.firstName = JOptionPane.showInputDialog(null, "First name");
                pupil.lastName  = JOptionPane.showInputDialog(null, "Last name");
                pupil.id        = Integer.parseInt(JOptionPane.showInputDialog(null, "ID"));

                JOptionPane.showMessageDialog(null, "One student is named: "
                     + fred.lastName + ", " + fred.firstName
                     + "\n and another is named: "
                     + pupil.lastName + ", " + pupil.firstName);
            }
        }


Data Hiding & Constructors

Purpose of this lesson

New Java language features

Good Practices


More reliable programs using private, getters, and setters

          TimeOfDay3 thatTime = new TimeOfDay3();
          thatTime.minute = 99;  // AVOIDS ANY VALIDITY CHECK
          thatTime.minute = userValue;  // AVOIDS ANY VALIDITY CHECK
          
          thatTime.minute++;            // WHAT HAPPENS AFTER 59?

Solution - private variables + public methods to get or set the private variables

Getters and Setters

          // File   : TimeOfDay3.java
          // Purpose: A 24 hour time-of-day class to demo intro OOP concepts.
          // Issues : Makes variables private, adds getters and setters.
          //
          public class TimeOfDay3 {
              //========================================= instance variables
              private int _hour;
              private int _minute;


              //================================================== getHour
              public int getHour() {
                  return _hour;
              }

              //================================================== setHour
              public void setHour(int h) {
                   if (h < 0 || h > 23) {
                       throw new IllegalArgumentException(
                           "TimeOfDay setHour: Bad hour value: " + h);
                   }
                   _hour = h;
              }

              //================================================ getMinute
              public int getMinute() {
                  return _minute;
              }

              //================================================ setMinute
              public void setMinute(int m) {
                  if (m < 0 || m > 59) {
                      throw new IllegalArgumentException(
                          "TimeOfDay setMinute: Bad minute value: " + m);
                  }
                  _minute = m;
              }
          }











          // File   : DemoTimeOfDay3.java
          // Purpose: Test the TimeOfDay3 class..
          //
          import javax.swing.*;

          public class DemoTimeOfDay3 {
              public static void main(String[] args) {

                  TimeOfDay3 then = new TimeOfDay3();
                  TimeOfDay3 now  = new TimeOfDay3();

                  // Code goes here to set then to 8:35 :


                  // Code goes here to set now to 14:05 :


                  //... Print the hours and minutes of the times.
                  JOptionPane.showMessageDialog(null,
                      "From " + then.getHour() + ":" + then.getMinute()
                    + " to " + now.getHour() + ":" + now.getMinute());

                  // THE FOLLOWING WOULD BE ILLEGAL
                  // now._hour = 99;   // Can't reference private variable.
              }
          }

Constructors

Add a constructor for better object initialization

Constructor Syntax

          // File   : TimeOfDay4.java
          // Purpose: A 24 hour time-of-day class to demo intro OOP concepts.
          // Issues : Makes variables private, adds getters and setters.
          //
          public class TimeOfDay4 {
              //========================================= instance variables
              private int _hour;
              private int _minute;


              //================================================ constructor
              public TimeOfDay4(int h, int m) {
                  //... Check values for validity.
                  if (h < 0 || h > 23 || m < 0 || m > 59) {
                      throw new IllegalArgumentException(
                          "TimeOfDay: Bad constructor value: " + h + ":" + m);
                  }
                  _hour   = h;
                  _minute = m;
              }


              //================================================== getHour
              public int getHour() {
                  return _hour;
              }

              //================================================== setHour
              public void setHour(int h) {
                  if (h < 0 || h > 23) {
                      throw new IllegalArgumentException(
                          "TimeOfDay setHour: Bad hour value: " + h);
                  }
                  _hour = h;
              }

              //================================================ getMinute
              public int getMinute() {
                  return _minute;
              }

              //================================================ setMinute
              public void setMinute(int m) {
                  if (m < 0 || m > 59) {
                      throw new IllegalArgumentException(
                          "TimeOfDay setMinute: Bad minute value: " + m);
                  }
                  _minute = m;
              }
          }












          // File   : DemoTimeOfDay4.java
          // Purpose: Test the TimeOfDay4 class.
          //
          import javax.swing.*;

          public class DemoTimeOfDay4 {
              public static void main(String[] args) {

                  // Use constructor:
                  TimeOfDay4 then = new TimeOfDay4(8, 35);
                  TimeOfDay4 now  = new TimeOfDay4(14, 5);

                  //... Print the hours and minutes of the times.
                  JOptionPane.showMessageDialog(null,
                      "From " + then.getHour() + ":" + then.getMinute()
                    + " to " + now.getHour() + ":" + now.getMinute());

                  // THE FOLLOWING WOULD BE ILLEGAL
                  // now._hour = 99;   // Can't reference private variable
              }
          }

Constructors & Default Instance Variable Values

        // DefVals.java:
        // Check default values that are assigned to class instance
        // variables.
        //
        class DefVals {
            private int anint;
            private int anotherint;
            private final int ANINTFINAL;
            private double adouble;
            private boolean aboolean;
            private String astring;


            // Default constructor will initialize ANINTFINAL and anint only:
            public DefVals() {
                ANINTFINAL = -255;
                anint = 255;
            }


            // Use toString() method to show value of all variables:
            public String toString() {
                String allvalues =  "anint: " + anint + "\n" +
                                    "anotherint: " + anotherint + "\n" +
                                    "ANINTFINAL: " + ANINTFINAL + "\n" +
                                    "adouble: " + adouble + "\n" +
                                    "aboolean: " + aboolean+ "\n" +
                                    "astring: " + astring + "\n";

                return allvalues;
            }
        }













        // TestDefVals.java:
        // Test the DefVals class.
        //
        public class TestDefVals {

            public static void main( String [] args ) {
    
                // Construct DefVals object using default constructor:
                DefVals dvobj = new DefVals();
    
    
                // Use dvobj's toString() method:
                System.out.println( dvobj );
                
                // also valid // System.out.println( dvobj.toString() );
    
            }
        
        }     


Overloading Methods and Constructors


Overloading Methods


Overloading Constructors

    TimeOfDay4.java contains:

        //================================================ constructor #1
        public TimeOfDay4(int h, int m) {
            // Can use set methods to set _hour and _minute:
            setHour( h );
            setMinute( m );
        }



    DemoTimeOfDay4.java contains:

            // Use constructor:
            TimeOfDay4 then = new TimeOfDay4(8, 35);
            TimeOfDay4 now  = new TimeOfDay4(14, 5);
            //================================================ constructor #2
            public TimeOfDay4( int h ) {
                setHour( h );
            }
            // Use 1-parameter overloaded TimeOfDay4 constructor:
            TimeOfDay4 later = new TimeOfDay4( 9 );
            //================================================ constructor #3
            public TimeOfDay4() {
                // An empty constructor body is legal.
            }
            // Use default constructor:
            TimeOfDay4 later = new TimeOfDay4();
            public class TimeOfDay4 {
                //========================================= instance variables
                private int _hour;
                private int _minute;

                // more variables added:
                private int _seconds;
                private bool twelveHour;   // 12-hour clock or 24-hour (military) clock
                private String ampm;       // either "AM" or "PM"
                
                
                // More constructors might be added, in addition to more get/set methods:
                //
                //================================================ constructor #4 
                public TimeOfDay4( int h, int m, int s ) {
                    setHour( h );
                    setMinute( m );
                    setSecond( s );
                }


               //================================================ constructor #5
               public TimeOfDay4( int h, int m, String ap ) {
                   setHour( h );
                   setMinute( m );
                   setTwelveHour( true );
                   setAmpm( ap );


               //
               // Additional get/set methods to be added after this
               //
    }

More on default constructors

               TimeOfDay now = new TimeOfDay();
               now.setHour( 8 );
               now.setMinute( 35 );
             // This also makes the code easier to understand.
             TimeOfDay now = new TimeOfDay( 8, 35 );