SlideShare a Scribd company logo
1 of 66
© 2012 Pearson Education, Inc. All rights reserved.

                                          Chapter 6:
                                    A First Look at Classes

                         Starting Out with Java:
              From Control Structures through Data Structures

                                                  Second Edition


                         by Tony Gaddis and Godfrey Muganda
Chapter Topics
      Chapter 6 discusses the following main topics:
             –   Classes and Objects
             –   Instance Fields and Methods
             –   Constructors
             –   Overloading Methods and Constructors
             –   Scope of Instance Fields
             –   Packages and Import Statements



© 2012 Pearson Education, Inc. All rights reserved.     6-2
Object-Oriented Programming
 • Object-oriented programming is centered on
   creating objects rather than procedures.
 • Objects are a melding of data and procedures
   that manipulate that data.
 • Data in an object are known as fields.
 • Procedures in an object are known as methods.



© 2012 Pearson Education, Inc. All rights reserved.   6-3
Object-Oriented Programming
                                                        Object
                                                      Data (Fields)




                                                   Methods
                                            That Operate on the Data

© 2012 Pearson Education, Inc. All rights reserved.                    6-4
Object-Oriented Programming
 • Object-oriented programming combines data
   and behavior via encapsulation.
 • Data hiding is the ability of an object to hide
   data from other objects in the program.
 • Only an object’s methods should be able to
   directly manipulate its data.
 • Other objects are allowed manipulate an
   object’s data via the object’s methods.

© 2012 Pearson Education, Inc. All rights reserved.   6-5
Object-Oriented Programming
                                                           Object
                                                       Data (Fields)
                                              typically private to this object




               Code
             Outside the
              Object



                                                        Methods That
                                                      Operate on the Data

© 2012 Pearson Education, Inc. All rights reserved.                              6-6
Object-Oriented Programming
 Data Hiding

 • Data hiding is important for several reasons.
       – It protects the data from accidental corruption by
         outside objects.
       – It hides the details of how an object works, so the
         programmer can concentrate on using it.
       – It allows the maintainer of the object to have the
         ability to modify the internal functioning of the
         object without “breaking” someone else's code.


© 2012 Pearson Education, Inc. All rights reserved.            6-7
Object-Oriented Programming
 Code Reusability

 • Object-Oriented Programming (OOP) has
   encouraged object reusability.
 • A software object contains data and methods that
   represents a specific concept or service.
 • An object is not a stand-alone program.
 • Objects can be used by programs that need the
   object’s service.
 • Reuse of code promotes the rapid development of
   larger software projects.

© 2012 Pearson Education, Inc. All rights reserved.   6-8
An Everyday Example of an Object—
 An Alarm Clock
      • Fields define the state that the alarm is currently in.
             –   The current second (a value in the range of 0-59)
             –   The current minute (a value in the range of 0-59)
             –   The current hour (a value in the range of 1-12)
             –   The time the alarm is set for (a valid hour and minute)
             –   Whether the alarm is on or off (“on” or “off”)




© 2012 Pearson Education, Inc. All rights reserved.                        6-9
An Everyday Example of an Object—
 An Alarm Clock
 • Methods are used to change a field’s value
       –    Set time
       –                               Public methods are
            Set alarm time
                                       accessed by users outside
       –    Turn alarm on              the object.
       –    Turn alarm off
       –    Increment the current second           Private methods
       –    Increment the current minute           are part of the
       –    Increment the current hour             object’s internal
       –                                           design.
            Sound alarm

© 2012 Pearson Education, Inc. All rights reserved.                    6-10
Classes and Objects
 • The programmer determines the fields and methods
   needed, and then creates a class.
 • A class can specify the fields and methods that a
   particular type of object may have.
 • A class is a “blueprint” that objects may be created
   from.
 • A class is not an object, but it can be a description of
   an object.
 • An object created from a class is called an instance of
   the class.

© 2012 Pearson Education, Inc. All rights reserved.           6-11
Classes and Objects
                                                             housefly object

               The Insect class defines the fields
            and methods that will exist in all objects    The housefly object is an
            that are an instances of the Insect class.   instance of the Insect class.




                            Insect class
                                                          The mosquito object is an
                                                         instance of the Insect class.



                                                            mosquito object



© 2012 Pearson Education, Inc. All rights reserved.                                      6-12
Classes
 • From chapter 2, we learned that a reference
   variable contains the address of an object.
       String cityName = "Charleston";

                                                       The object that contains the
                                                      character string “Charleston”


 cityName             Address to the object                   Charleston



© 2012 Pearson Education, Inc. All rights reserved.                              6-13
Classes
 • The length() method of the String class
   returns and integer value that is equal to the
   length of the string.
       int stringLength = cityName.length();
 • Class objects normally have methods that
   perform useful operations on their data.
 • Primitive variables can only store data and have
   no methods.

© 2012 Pearson Education, Inc. All rights reserved.   6-14
Classes and Instances
 • Many objects can be created from a class.
 • Each object is independent of the others.
       String person = "Jenny ";
       String pet = "Fido";
       String favoriteColor = "Blue";




© 2012 Pearson Education, Inc. All rights reserved.   6-15
Classes and Instances

                     person             Address       “Jenny”



                          pet           Address       “Fido”



    favoriteColor                       Address       “Blue”



© 2012 Pearson Education, Inc. All rights reserved.             6-16
Classes and Instances
 • Each instance of the String class contains different
   data.
 • The instances are all share the same design.
 • Each instance has all of the attributes and methods that
   were defined in the String class.
 • Classes are defined to represent a single concept or
   service.




© 2012 Pearson Education, Inc. All rights reserved.           6-17
Building a Rectangle class
 • A Rectangle object will have the following
   fields:
       – length. The length field will hold the rectangle’s
         length.
       – width. The width field will hold the rectangle’s
         width.




© 2012 Pearson Education, Inc. All rights reserved.           6-18
Building a Rectangle class
   • The Rectangle class will also have the
     following methods:
          – setLength. The setLength method will store a
            value in an object’s length field.
          – setWidth. The setWidth method will store a value
            in an object’s width field.
          – getLength. The getLength method will return the
            value in an object’s length field.
          – getWidth. The getWidth method will return the
            value in an object’s width field.
          – getArea. The getArea method will return the area
            of the rectangle, which is the result of the object’s
            length multiplied by its width.
© 2012 Pearson Education, Inc. All rights reserved.                 6-19
UML Diagram
 • Unified Modeling Language (UML) provides a
   set of standard diagrams for graphically
   depicting object-oriented systems.

       Class name goes here

       Fields are listed here

       Methods are listed here


© 2012 Pearson Education, Inc. All rights reserved.   6-20
UML Diagram for
 Rectangle class

                                                      Rectangle

                                     length
                                     width

                                     setLength()
                                     setWidth()
                                     getLength()
                                     getWidth()
                                     getArea()


© 2012 Pearson Education, Inc. All rights reserved.               6-21
Writing the Code for the Class Fields

       public class Rectangle
       {
           private double length;
           private double width;
       }



© 2012 Pearson Education, Inc. All rights reserved.   6-22
Access Specifiers
 • An access specifier is a Java keyword that indicates
   how a field or method can be accessed.
 • public
       – When the public access specifier is applied to a class
         member, the member can be accessed by code inside the
         class or outside.
 • private
       – When the private access specifier is applied to a class
         member, the member cannot be accessed by code outside the
         class. The member can be accessed only by methods that
         are members of the same class.

© 2012 Pearson Education, Inc. All rights reserved.                  6-23
Header for the setLength Method
                          Return                               Notice the word
                          Type                                 static does not
    Access                                            Method   appear in the method
   specifier                                          Name     header designed to work
                                                               on an instance of a class
                                                               (instance method).

 public void setLength (double len)

          Parameter variable declaration


© 2012 Pearson Education, Inc. All rights reserved.                                        6-24
Writing and Demonstrating the
 setLength Method
       /**
          The setLength method stores a value in the
          length field.
          @param len The value to store in length.
       */
       public void setLength(double len)
       {
          length = len;
       }

    Examples: Rectangle.java, LengthDemo.java

© 2012 Pearson Education, Inc. All rights reserved.    6-25
Creating a Rectangle object

  Rectangle box = new Rectangle ();
                                                      A Rectangle object
            The box
          variable holds                                 length:   0.0
          the address of                    address
          the Rectangle                                  width:    0.0
              object.




© 2012 Pearson Education, Inc. All rights reserved.                        6-26
Calling the setLength Method

                 box.setLength(10.0);
            The box                                   A Rectangle object
          variable holds
          the address of                                 length: 10.0
                                            address
                the                                      width: 0.0
          Rectangle
              object.

                 This is the state of the box object after
                  the setLength method executes.
© 2012 Pearson Education, Inc. All rights reserved.                        6-27
Writing the getLength Method
             /**
                The getLength method returns a Rectangle
                object's length.
                @return The value in the length field.
             */
             public double getLength()
             {
                return length;
             }
      Similarly, the setWidth and getWidth methods
        can be created.
      Examples: Rectangle.java, LengthWidthDemo.java

© 2012 Pearson Education, Inc. All rights reserved.        6-28
Writing and Demonstrating the getArea
 Method
       /**
              The getArea method returns a Rectangle
              object's area.
              @return The product of length times width.
       */
       public double getArea()
       {
          return length * width;
       }
 Examples: Rectangle.java, RectangleDemo.java


© 2012 Pearson Education, Inc. All rights reserved.        6-29
Accessor and Mutator Methods
 • Because of the concept of data hiding, fields in a class
   are private.
 • The methods that retrieve the data of fields are called
   accessors.
 • The methods that modify the data of fields are called
   mutators.
 • Each field that the programmer wishes to be viewed by
   other classes needs an accessor.
 • Each field that the programmer wishes to be modified
   by other classes needs a mutator.

© 2012 Pearson Education, Inc. All rights reserved.           6-30
Accessors and Mutators
 • For the Rectangle example, the accessors and
   mutators are:
       – setLength : Sets the value of the length field.
              public void setLength(double len) …
       – setWidth                 : Sets the value of the width field.
              public void setLength(double w) …
       – getLength : Returns the value of the length field.
              public double getLength() …
       – getWidth                 : Returns the value of the width field.
              public double getWidth() …

 • Other names for these methods are getters and setters.

© 2012 Pearson Education, Inc. All rights reserved.                         6-31
Stale Data
 • Some data is the result of a calculation.
 • Consider the area of a rectangle.
       – length × width
 • It would be impractical to use an area variable here.
 • Data that requires the calculation of various factors has
   the potential to become stale.
 • To avoid stale data, it is best to calculate the value of
   that data within a method rather than store it in a
   variable.

© 2012 Pearson Education, Inc. All rights reserved.            6-32
Stale Data
 • Rather than use an area variable in a Rectangle
   class:
       public double getArea()
       {
         return length * width;
       }
 • This dynamically calculates the value of the
   rectangle’s area when the method is called.
 • Now, any change to the length or width variables
   will not leave the area of the rectangle stale.

© 2012 Pearson Education, Inc. All rights reserved.   6-33
UML Data Type and Parameter Notation
 • UML diagrams are language independent.
 • UML diagrams use an independent notation to show
   return types, access modifiers, etc.


          Access modifiers                                  Rectangle
          are denoted as:
               + public
               - private                          - width : double


                                                  + setWidth(w : double) : void


© 2012 Pearson Education, Inc. All rights reserved.                               6-34
UML Data Type and Parameter Notation
 • UML diagrams are language independent.
 • UML diagrams use an independent notation to show
   return types, access modifiers, etc.
                                                                     Variable types are
                                                      Rectangle      placed after the variable
                                                                     name, separated by a
                                                                     colon.
                                     - width : double


                                     + setWidth(w : double) : void


© 2012 Pearson Education, Inc. All rights reserved.                                       6-35
UML Data Type and Parameter Notation
 • UML diagrams are language independent.
 • UML diagrams use an independent notation to show
   return types, access modifiers, etc.

                                                                     Method return types are
                                                      Rectangle      placed after the method
                                                                     declaration name,
                                                                     separated by a colon.
                                     - width : double


                                     + setWidth(w : double) : void


© 2012 Pearson Education, Inc. All rights reserved.                                        6-36
UML Data Type and Parameter Notation
 • UML diagrams are language independent.
 • UML diagrams use an independent notation to show
   return types, access modifiers, etc.

Method parameters
are shown inside the                                  Rectangle
parentheses using the
same notation as
variables.                           - width : double


                                     + setWidth(w : double) : void


© 2012 Pearson Education, Inc. All rights reserved.                  6-37
Converting the UML Diagram to Code

 • Putting all of this information together, a Java class
   file can be built easily using the UML diagram.
 • The UML diagram parts match the Java class file
   structure.


                       class header
                                                      ClassName
                       {
                         Fields                         Fields
                         Methods                       Methods
                       }

© 2012 Pearson Education, Inc. All rights reserved.               6-38
Converting the UML Diagram to Code
                                                      public class Rectangle
The structure of the class can be                     {
compiled and tested without having                       private double width;
bodies for the methods. Just be sure to                  private double length;
put in dummy return values for methods
that have a return type other than void.                  public void setWidth(double w)
                                                          {
                                                          }
                Rectangle                                 public void setLength(double len)
                                                          {
 - width : double                                         }
 - length : double                                        public double getWidth()
                                                          {    return 0.0;
 + setWidth(w : double) : void                            }
                                                          public double getLength()
 + setLength(len : double): void                          {    return 0.0;
 + getWidth() : double                                    }
 + getLength() : double                                   public double getArea()
 + getArea() : double                                     {    return 0.0;
                                                          }
                                                      }
© 2012 Pearson Education, Inc. All rights reserved.                                       6-39
Converting the UML Diagram to Code
                                                      public class Rectangle
Once the class structure has been tested,             {
                                                         private double width;
the method bodies can be written and
                                                         private double length;
tested.
                                                          public void setWidth(double w)
                                                          {    width = w;
                                                          }
                Rectangle                                 public void setLength(double len)
                                                          {    length = len;
 - width : double                                         }
 - length : double                                        public double getWidth()
                                                          {    return width;
                                                          }
 + setWidth(w : double) : void                            public double getLength()
 + setLength(len : double): void                          {    return length;
 + getWidth() : double                                    }
 + getLength() : double                                   public double getArea()
                                                          {    return length * width;
 + getArea() : double                                     }
                                                      }
© 2012 Pearson Education, Inc. All rights reserved.                                       6-40
Class Layout Conventions
 • The layout of a source code file can vary by
   employer or instructor.
 • A common layout is:
       – Fields listed first
       – Methods listed second
              • Accessors and mutators are typically grouped.
 • There are tools that can help in formatting
   layout to specific standards.

© 2012 Pearson Education, Inc. All rights reserved.             6-41
Instance Fields and Methods
 • Fields and methods that are declared as
   previously shown are called instance fields and
   instance methods.
 • Objects created from a class each have their
   own copy of instance fields.
 • Instance methods are methods that are not
   declared with a special keyword, static.


© 2012 Pearson Education, Inc. All rights reserved.   6-42
Instance Fields and Methods
 • Instance fields and instance methods require an
   object to be created in order to be used.
 • See example: RoomAreas.java
 • Note that each room represented in this
   example can have different dimensions.
              Rectangle kitchen = new Rectangle();
              Rectangle bedroom = new Rectangle();
              Rectangle den = new Rectangle();




© 2012 Pearson Education, Inc. All rights reserved.   6-43
States of Three Different Rectangle
 Objects
    The kitchen variable                              length: 10.0
    holds the address of a                  address
    Rectangle Object.                                 width: 14.0

    The bedroom variable                              length: 15.0
    holds the address of a                  address
    Rectangle Object.                                 width: 12.0

    The den variable                                  length: 20.0
    holds the address of a                  address
    Rectangle Object.                                 width: 30.0


© 2012 Pearson Education, Inc. All rights reserved.                  6-44
Constructors
 • Classes can have special methods called constructors.
 • A constructor is a method that is automatically called
   when an object is created.
 • Constructors are used to perform operations at the time
   an object is created.
 • Constructors typically initialize instance fields and
   perform other object initialization tasks.




© 2012 Pearson Education, Inc. All rights reserved.          6-45
Constructors
 • Constructors have a few special properties that
   set them apart from normal methods.
       –    Constructors have the same name as the class.
       –    Constructors have no return type (not even void).
       –    Constructors may not return any values.
       –    Constructors are typically public.




© 2012 Pearson Education, Inc. All rights reserved.             6-46
Constructor for Rectangle Class
       /**
              Constructor
              @param len The length of the rectangle.
              @param w The width of the rectangle.
       */
       public Rectangle(double len, double w)
       {
          length = len;
          width = w;
       }
 Examples: Rectangle.java, ConstructorDemo.java

© 2012 Pearson Education, Inc. All rights reserved.     6-47
Constructors in UML
 • In UML, the most common way constructors
   are defined is:
                                 Rectangle
                                                      Notice there is no
                                                      return type listed
             - width : double                         for constructors.
             - length : double
             +Rectangle(len:double, w:double)
             + setWidth(w : double) : void
             + setLength(len : double): void
             + getWidth() : double
             + getLength() : double
             + getArea() : double


© 2012 Pearson Education, Inc. All rights reserved.                        6-48
Uninitialized Local Reference Variables
 • Reference variables can be declared without being initialized.
       Rectangle box;
 • This statement does not create a Rectangle object, so it is an
   uninitialized local reference variable.
 • A local reference variable must reference an object before it can
   be used, otherwise a compiler error will occur.
              box = new Rectangle(7.0, 14.0);
 • box will now reference a Rectangle object of length 7.0 and
   width 14.0.



© 2012 Pearson Education, Inc. All rights reserved.                    6-49
The Default Constructor
 • When an object is created, its constructor is always
   called.
 • If you do not write a constructor, Java provides one
   when the class is compiled. The constructor that Java
   provides is known as the default constructor.
       – It sets all of the object’s numeric fields to 0.
       – It sets all of the object’s boolean fields to false.
       – It sets all of the object’s reference variables to the special
         value null.


© 2012 Pearson Education, Inc. All rights reserved.                       6-50
The Default Constructor
 • The default constructor is a constructor with no
   parameters, used to initialize an object in a default
   configuration.
 • The only time that Java provides a default constructor
   is when you do not write any constructor for a class.
       – See example: First version of Rectangle.java
 • A default constructor is not provided by Java if a
   constructor is already written.
       – See example: Rectangle.java with Constructor


© 2012 Pearson Education, Inc. All rights reserved.         6-51
Writing Your Own No-Arg Constructor
 • A constructor that does not accept arguments is known
   as a no-arg constructor.
 • The default constructor (provided by Java) is a no-arg
   constructor.
 • We can write our own no-arg constructor

              public Rectangle()
              {
                   length = 1.0;
                   width = 1.0;
              }
© 2012 Pearson Education, Inc. All rights reserved.         6-52
The String Class Constructor
 • One of the String class constructors accepts
   a string literal as an argument.
 • This string literal is used to initialize a String
   object.
 • For instance:

 String name = new String("Michael Long");



© 2012 Pearson Education, Inc. All rights reserved.     6-53
The String Class Constructor
 • This creates a new reference variable name that points
   to a String object that represents the name “Michael
   Long”
 • Because they are used so often, String objects can
   be created with a shorthand:

       String name = "Michael Long";




© 2012 Pearson Education, Inc. All rights reserved.         6-54
Overloading Methods and Constructors
 • Two or more methods in a class may have the
   same name as long as their parameter lists are
   different.
 • When this occurs, it is called method
   overloading. This also applies to constructors.
 • Method overloading is important because
   sometimes you need several different ways to
   perform the same operation.

© 2012 Pearson Education, Inc. All rights reserved.   6-55
Overloaded Method add
 public int add(int num1, int num2)
 {
   int sum = num1 + num2;
   return sum;
 }

 public String add (String str1, String str2)
 {
   String combined = str1 + str2;
   return combined;
 }

© 2012 Pearson Education, Inc. All rights reserved.   6-56
Method Signature and Binding
 • A method signature consists of the method’s name and the data
   types of the method’s parameters, in the order that they appear.
   The return type is not part of the signature.
                                                      Signatures of the
       add(int, int)
                                                       add methods of
       add(String, String)
                                                        previous slide
 • The process of matching a method call with the correct method
   is known as binding. The compiler uses the method signature
   to determine which version of the overloaded method to bind
   the call to.


© 2012 Pearson Education, Inc. All rights reserved.                       6-57
Rectangle Class Constructor Overload
 If we were to add the no-arg constructor we wrote
    previously to our Rectangle class in addition to the
    original constructor we wrote, what would happen
    when we execute the following calls?

       Rectangle box1 = new Rectangle();
       Rectangle box2 = new Rectangle(5.0, 10.0);




© 2012 Pearson Education, Inc. All rights reserved.        6-58
Rectangle Class Constructor Overload
 If we were to add the no-arg constructor we wrote
    previously to our Rectangle class in addition to the
    original constructor we wrote, what would happen
    when we execute the following calls?

       Rectangle box1 = new Rectangle();
       Rectangle box2 = new Rectangle(5.0, 10.0);

 The first call would use the no-arg constructor and box1 would
   have a length of 1.0 and width of 1.0.
 The second call would use the original constructor and box2
   would have a length of 5.0 and a width of 10.0.

© 2012 Pearson Education, Inc. All rights reserved.               6-59
The BankAccount Example
     BankAccount.java                                              BankAccount
     AccountTest.java                                  -balance:double

                                                       +BankAccount()

     Overloaded Constructors                           +BankAccount(startBalance:double)
                                                       +BankAccount(strString):
                                                       +deposit(amount:double):void
 Overloaded deposit methods
                                                       +deposit(str:String):void
                                                       +withdraw(amount:double):void
 Overloaded withdraw methods
                                                       +withdraw(str:String):void
                                                       +setBalance(b:double):void
Overloaded setBalance methods
                                                       +setBalance(str:String):void
                                                       +getBalance():double


 © 2012 Pearson Education, Inc. All rights reserved.                                       6-60
Scope of Instance Fields
 • Variables declared as instance fields in a class
   can be accessed by any instance method in the
   same class as the field.
 • If an instance field is declared with the
   public access specifier, it can also be
   accessed by code outside the class, as long as
   an instance of the class exists.


© 2012 Pearson Education, Inc. All rights reserved.   6-61
Shadowing
      • A parameter variable is, in effect, a local variable.
      • Within a method, variable names must be unique.
      • A method may have a local variable with the same name as
        an instance field.
      • This is called shadowing.
      • The local variable will hide the value of the instance field.
      • Shadowing is discouraged and local variable names should
        not be the same as instance field names.




© 2012 Pearson Education, Inc. All rights reserved.                     6-62
Packages and import Statements
      • Classes in the Java API are organized into packages.
      • Explicit and Wildcard import statements
             – Explicit imports name a specific class
                    • import java.util.Scanner;
             – Wildcard imports name a package, followed by an *
                    • import java.util.*;

      • The java.lang package is automatically made
        available to any Java class.



© 2012 Pearson Education, Inc. All rights reserved.                6-63
Some Java Standard Packages




© 2012 Pearson Education, Inc. All rights reserved.   6-64
Object Oriented Design
 Finding Classes and Their Responsibilities

      • Finding the classes
             – Get written description of the problem domain
             – Identify all nouns, each is a potential class
             – Refine list to include only classes relevant to the
               problem

      • Identify the responsibilities
             – Things a class is responsible for knowing
             – Things a class is responsible for doing
             – Refine list to include only classes relevant to the
               problem



© 2012 Pearson Education, Inc. All rights reserved.                  6-65
Object Oriented Design
 Finding Classes and Their Responsibilities

      – Identify the responsibilities
             • Things a class is responsible for knowing
             • Things a class is responsible for doing
             • Refine list to include only classes relevant to the problem




© 2012 Pearson Education, Inc. All rights reserved.                          6-66

More Related Content

What's hot

Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)HarshithaAllu
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHoang Nguyen
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programmingHariz Mustafa
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Hitesh-Java
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetdevlabsalliance
 

What's hot (15)

Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)GETTING STARTED WITH JAVA(beginner)
GETTING STARTED WITH JAVA(beginner)
 
0 E158 C10d01
0 E158 C10d010 E158 C10d01
0 E158 C10d01
 
ANDROID FDP PPT
ANDROID FDP PPTANDROID FDP PPT
ANDROID FDP PPT
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Chap3java5th
Chap3java5thChap3java5th
Chap3java5th
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Swing api
Swing apiSwing api
Swing api
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Inheritance
InheritanceInheritance
Inheritance
 
Chap1java5th
Chap1java5thChap1java5th
Chap1java5th
 
Chap5java5th
Chap5java5thChap5java5th
Chap5java5th
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 

Similar to Java Class Fundamentals

Similar to Java Class Fundamentals (20)

Cso gaddis java_chapter6
Cso gaddis java_chapter6Cso gaddis java_chapter6
Cso gaddis java_chapter6
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Chapter 4 Writing Classes
Chapter 4 Writing ClassesChapter 4 Writing Classes
Chapter 4 Writing Classes
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
1 unit (oops)
1 unit (oops)1 unit (oops)
1 unit (oops)
 
Introduction to Object Oriented databases
Introduction to Object Oriented databasesIntroduction to Object Oriented databases
Introduction to Object Oriented databases
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
 
Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
M01_OO_Intro.ppt
M01_OO_Intro.pptM01_OO_Intro.ppt
M01_OO_Intro.ppt
 
Cso gaddis java_chapter11
Cso gaddis java_chapter11Cso gaddis java_chapter11
Cso gaddis java_chapter11
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
OOP
OOPOOP
OOP
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
80410172053.pdf
80410172053.pdf80410172053.pdf
80410172053.pdf
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
 
Bt8901 objective oriented systems1
Bt8901 objective oriented systems1Bt8901 objective oriented systems1
Bt8901 objective oriented systems1
 

More from mlrbrown

Cso gaddis java_chapter15
Cso gaddis java_chapter15Cso gaddis java_chapter15
Cso gaddis java_chapter15mlrbrown
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12mlrbrown
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10mlrbrown
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8mlrbrown
 
Cso gaddis java_chapter3
Cso gaddis java_chapter3Cso gaddis java_chapter3
Cso gaddis java_chapter3mlrbrown
 
Cso gaddis java_chapter1
Cso gaddis java_chapter1Cso gaddis java_chapter1
Cso gaddis java_chapter1mlrbrown
 
Networking Chapter 16
Networking Chapter 16Networking Chapter 16
Networking Chapter 16mlrbrown
 
Networking Chapter 15
Networking Chapter 15Networking Chapter 15
Networking Chapter 15mlrbrown
 
Networking Chapter 14
Networking Chapter 14Networking Chapter 14
Networking Chapter 14mlrbrown
 
Networking Chapter 13
Networking Chapter 13Networking Chapter 13
Networking Chapter 13mlrbrown
 
Networking Chapter 12
Networking Chapter 12Networking Chapter 12
Networking Chapter 12mlrbrown
 
Networking Chapter 11
Networking Chapter 11Networking Chapter 11
Networking Chapter 11mlrbrown
 
Networking Chapter 10
Networking Chapter 10Networking Chapter 10
Networking Chapter 10mlrbrown
 
Networking Chapter 9
Networking Chapter 9Networking Chapter 9
Networking Chapter 9mlrbrown
 
Networking Chapter 7
Networking Chapter 7Networking Chapter 7
Networking Chapter 7mlrbrown
 
Networking Chapter 8
Networking Chapter 8Networking Chapter 8
Networking Chapter 8mlrbrown
 
Student Orientation
Student OrientationStudent Orientation
Student Orientationmlrbrown
 
Networking Chapter 6
Networking Chapter 6Networking Chapter 6
Networking Chapter 6mlrbrown
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5mlrbrown
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4mlrbrown
 

More from mlrbrown (20)

Cso gaddis java_chapter15
Cso gaddis java_chapter15Cso gaddis java_chapter15
Cso gaddis java_chapter15
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
Cso gaddis java_chapter3
Cso gaddis java_chapter3Cso gaddis java_chapter3
Cso gaddis java_chapter3
 
Cso gaddis java_chapter1
Cso gaddis java_chapter1Cso gaddis java_chapter1
Cso gaddis java_chapter1
 
Networking Chapter 16
Networking Chapter 16Networking Chapter 16
Networking Chapter 16
 
Networking Chapter 15
Networking Chapter 15Networking Chapter 15
Networking Chapter 15
 
Networking Chapter 14
Networking Chapter 14Networking Chapter 14
Networking Chapter 14
 
Networking Chapter 13
Networking Chapter 13Networking Chapter 13
Networking Chapter 13
 
Networking Chapter 12
Networking Chapter 12Networking Chapter 12
Networking Chapter 12
 
Networking Chapter 11
Networking Chapter 11Networking Chapter 11
Networking Chapter 11
 
Networking Chapter 10
Networking Chapter 10Networking Chapter 10
Networking Chapter 10
 
Networking Chapter 9
Networking Chapter 9Networking Chapter 9
Networking Chapter 9
 
Networking Chapter 7
Networking Chapter 7Networking Chapter 7
Networking Chapter 7
 
Networking Chapter 8
Networking Chapter 8Networking Chapter 8
Networking Chapter 8
 
Student Orientation
Student OrientationStudent Orientation
Student Orientation
 
Networking Chapter 6
Networking Chapter 6Networking Chapter 6
Networking Chapter 6
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

Java Class Fundamentals

  • 1. © 2012 Pearson Education, Inc. All rights reserved. Chapter 6: A First Look at Classes Starting Out with Java: From Control Structures through Data Structures Second Edition by Tony Gaddis and Godfrey Muganda
  • 2. Chapter Topics Chapter 6 discusses the following main topics: – Classes and Objects – Instance Fields and Methods – Constructors – Overloading Methods and Constructors – Scope of Instance Fields – Packages and Import Statements © 2012 Pearson Education, Inc. All rights reserved. 6-2
  • 3. Object-Oriented Programming • Object-oriented programming is centered on creating objects rather than procedures. • Objects are a melding of data and procedures that manipulate that data. • Data in an object are known as fields. • Procedures in an object are known as methods. © 2012 Pearson Education, Inc. All rights reserved. 6-3
  • 4. Object-Oriented Programming Object Data (Fields) Methods That Operate on the Data © 2012 Pearson Education, Inc. All rights reserved. 6-4
  • 5. Object-Oriented Programming • Object-oriented programming combines data and behavior via encapsulation. • Data hiding is the ability of an object to hide data from other objects in the program. • Only an object’s methods should be able to directly manipulate its data. • Other objects are allowed manipulate an object’s data via the object’s methods. © 2012 Pearson Education, Inc. All rights reserved. 6-5
  • 6. Object-Oriented Programming Object Data (Fields) typically private to this object Code Outside the Object Methods That Operate on the Data © 2012 Pearson Education, Inc. All rights reserved. 6-6
  • 7. Object-Oriented Programming Data Hiding • Data hiding is important for several reasons. – It protects the data from accidental corruption by outside objects. – It hides the details of how an object works, so the programmer can concentrate on using it. – It allows the maintainer of the object to have the ability to modify the internal functioning of the object without “breaking” someone else's code. © 2012 Pearson Education, Inc. All rights reserved. 6-7
  • 8. Object-Oriented Programming Code Reusability • Object-Oriented Programming (OOP) has encouraged object reusability. • A software object contains data and methods that represents a specific concept or service. • An object is not a stand-alone program. • Objects can be used by programs that need the object’s service. • Reuse of code promotes the rapid development of larger software projects. © 2012 Pearson Education, Inc. All rights reserved. 6-8
  • 9. An Everyday Example of an Object— An Alarm Clock • Fields define the state that the alarm is currently in. – The current second (a value in the range of 0-59) – The current minute (a value in the range of 0-59) – The current hour (a value in the range of 1-12) – The time the alarm is set for (a valid hour and minute) – Whether the alarm is on or off (“on” or “off”) © 2012 Pearson Education, Inc. All rights reserved. 6-9
  • 10. An Everyday Example of an Object— An Alarm Clock • Methods are used to change a field’s value – Set time – Public methods are Set alarm time accessed by users outside – Turn alarm on the object. – Turn alarm off – Increment the current second Private methods – Increment the current minute are part of the – Increment the current hour object’s internal – design. Sound alarm © 2012 Pearson Education, Inc. All rights reserved. 6-10
  • 11. Classes and Objects • The programmer determines the fields and methods needed, and then creates a class. • A class can specify the fields and methods that a particular type of object may have. • A class is a “blueprint” that objects may be created from. • A class is not an object, but it can be a description of an object. • An object created from a class is called an instance of the class. © 2012 Pearson Education, Inc. All rights reserved. 6-11
  • 12. Classes and Objects housefly object The Insect class defines the fields and methods that will exist in all objects The housefly object is an that are an instances of the Insect class. instance of the Insect class. Insect class The mosquito object is an instance of the Insect class. mosquito object © 2012 Pearson Education, Inc. All rights reserved. 6-12
  • 13. Classes • From chapter 2, we learned that a reference variable contains the address of an object. String cityName = "Charleston"; The object that contains the character string “Charleston” cityName Address to the object Charleston © 2012 Pearson Education, Inc. All rights reserved. 6-13
  • 14. Classes • The length() method of the String class returns and integer value that is equal to the length of the string. int stringLength = cityName.length(); • Class objects normally have methods that perform useful operations on their data. • Primitive variables can only store data and have no methods. © 2012 Pearson Education, Inc. All rights reserved. 6-14
  • 15. Classes and Instances • Many objects can be created from a class. • Each object is independent of the others. String person = "Jenny "; String pet = "Fido"; String favoriteColor = "Blue"; © 2012 Pearson Education, Inc. All rights reserved. 6-15
  • 16. Classes and Instances person Address “Jenny” pet Address “Fido” favoriteColor Address “Blue” © 2012 Pearson Education, Inc. All rights reserved. 6-16
  • 17. Classes and Instances • Each instance of the String class contains different data. • The instances are all share the same design. • Each instance has all of the attributes and methods that were defined in the String class. • Classes are defined to represent a single concept or service. © 2012 Pearson Education, Inc. All rights reserved. 6-17
  • 18. Building a Rectangle class • A Rectangle object will have the following fields: – length. The length field will hold the rectangle’s length. – width. The width field will hold the rectangle’s width. © 2012 Pearson Education, Inc. All rights reserved. 6-18
  • 19. Building a Rectangle class • The Rectangle class will also have the following methods: – setLength. The setLength method will store a value in an object’s length field. – setWidth. The setWidth method will store a value in an object’s width field. – getLength. The getLength method will return the value in an object’s length field. – getWidth. The getWidth method will return the value in an object’s width field. – getArea. The getArea method will return the area of the rectangle, which is the result of the object’s length multiplied by its width. © 2012 Pearson Education, Inc. All rights reserved. 6-19
  • 20. UML Diagram • Unified Modeling Language (UML) provides a set of standard diagrams for graphically depicting object-oriented systems. Class name goes here Fields are listed here Methods are listed here © 2012 Pearson Education, Inc. All rights reserved. 6-20
  • 21. UML Diagram for Rectangle class Rectangle length width setLength() setWidth() getLength() getWidth() getArea() © 2012 Pearson Education, Inc. All rights reserved. 6-21
  • 22. Writing the Code for the Class Fields public class Rectangle { private double length; private double width; } © 2012 Pearson Education, Inc. All rights reserved. 6-22
  • 23. Access Specifiers • An access specifier is a Java keyword that indicates how a field or method can be accessed. • public – When the public access specifier is applied to a class member, the member can be accessed by code inside the class or outside. • private – When the private access specifier is applied to a class member, the member cannot be accessed by code outside the class. The member can be accessed only by methods that are members of the same class. © 2012 Pearson Education, Inc. All rights reserved. 6-23
  • 24. Header for the setLength Method Return Notice the word Type static does not Access Method appear in the method specifier Name header designed to work on an instance of a class (instance method). public void setLength (double len) Parameter variable declaration © 2012 Pearson Education, Inc. All rights reserved. 6-24
  • 25. Writing and Demonstrating the setLength Method /** The setLength method stores a value in the length field. @param len The value to store in length. */ public void setLength(double len) { length = len; } Examples: Rectangle.java, LengthDemo.java © 2012 Pearson Education, Inc. All rights reserved. 6-25
  • 26. Creating a Rectangle object Rectangle box = new Rectangle (); A Rectangle object The box variable holds length: 0.0 the address of address the Rectangle width: 0.0 object. © 2012 Pearson Education, Inc. All rights reserved. 6-26
  • 27. Calling the setLength Method box.setLength(10.0); The box A Rectangle object variable holds the address of length: 10.0 address the width: 0.0 Rectangle object. This is the state of the box object after the setLength method executes. © 2012 Pearson Education, Inc. All rights reserved. 6-27
  • 28. Writing the getLength Method /** The getLength method returns a Rectangle object's length. @return The value in the length field. */ public double getLength() { return length; } Similarly, the setWidth and getWidth methods can be created. Examples: Rectangle.java, LengthWidthDemo.java © 2012 Pearson Education, Inc. All rights reserved. 6-28
  • 29. Writing and Demonstrating the getArea Method /** The getArea method returns a Rectangle object's area. @return The product of length times width. */ public double getArea() { return length * width; } Examples: Rectangle.java, RectangleDemo.java © 2012 Pearson Education, Inc. All rights reserved. 6-29
  • 30. Accessor and Mutator Methods • Because of the concept of data hiding, fields in a class are private. • The methods that retrieve the data of fields are called accessors. • The methods that modify the data of fields are called mutators. • Each field that the programmer wishes to be viewed by other classes needs an accessor. • Each field that the programmer wishes to be modified by other classes needs a mutator. © 2012 Pearson Education, Inc. All rights reserved. 6-30
  • 31. Accessors and Mutators • For the Rectangle example, the accessors and mutators are: – setLength : Sets the value of the length field. public void setLength(double len) … – setWidth : Sets the value of the width field. public void setLength(double w) … – getLength : Returns the value of the length field. public double getLength() … – getWidth : Returns the value of the width field. public double getWidth() … • Other names for these methods are getters and setters. © 2012 Pearson Education, Inc. All rights reserved. 6-31
  • 32. Stale Data • Some data is the result of a calculation. • Consider the area of a rectangle. – length × width • It would be impractical to use an area variable here. • Data that requires the calculation of various factors has the potential to become stale. • To avoid stale data, it is best to calculate the value of that data within a method rather than store it in a variable. © 2012 Pearson Education, Inc. All rights reserved. 6-32
  • 33. Stale Data • Rather than use an area variable in a Rectangle class: public double getArea() { return length * width; } • This dynamically calculates the value of the rectangle’s area when the method is called. • Now, any change to the length or width variables will not leave the area of the rectangle stale. © 2012 Pearson Education, Inc. All rights reserved. 6-33
  • 34. UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Access modifiers Rectangle are denoted as: + public - private - width : double + setWidth(w : double) : void © 2012 Pearson Education, Inc. All rights reserved. 6-34
  • 35. UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Variable types are Rectangle placed after the variable name, separated by a colon. - width : double + setWidth(w : double) : void © 2012 Pearson Education, Inc. All rights reserved. 6-35
  • 36. UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Method return types are Rectangle placed after the method declaration name, separated by a colon. - width : double + setWidth(w : double) : void © 2012 Pearson Education, Inc. All rights reserved. 6-36
  • 37. UML Data Type and Parameter Notation • UML diagrams are language independent. • UML diagrams use an independent notation to show return types, access modifiers, etc. Method parameters are shown inside the Rectangle parentheses using the same notation as variables. - width : double + setWidth(w : double) : void © 2012 Pearson Education, Inc. All rights reserved. 6-37
  • 38. Converting the UML Diagram to Code • Putting all of this information together, a Java class file can be built easily using the UML diagram. • The UML diagram parts match the Java class file structure. class header ClassName { Fields Fields Methods Methods } © 2012 Pearson Education, Inc. All rights reserved. 6-38
  • 39. Converting the UML Diagram to Code public class Rectangle The structure of the class can be { compiled and tested without having private double width; bodies for the methods. Just be sure to private double length; put in dummy return values for methods that have a return type other than void. public void setWidth(double w) { } Rectangle public void setLength(double len) { - width : double } - length : double public double getWidth() { return 0.0; + setWidth(w : double) : void } public double getLength() + setLength(len : double): void { return 0.0; + getWidth() : double } + getLength() : double public double getArea() + getArea() : double { return 0.0; } } © 2012 Pearson Education, Inc. All rights reserved. 6-39
  • 40. Converting the UML Diagram to Code public class Rectangle Once the class structure has been tested, { private double width; the method bodies can be written and private double length; tested. public void setWidth(double w) { width = w; } Rectangle public void setLength(double len) { length = len; - width : double } - length : double public double getWidth() { return width; } + setWidth(w : double) : void public double getLength() + setLength(len : double): void { return length; + getWidth() : double } + getLength() : double public double getArea() { return length * width; + getArea() : double } } © 2012 Pearson Education, Inc. All rights reserved. 6-40
  • 41. Class Layout Conventions • The layout of a source code file can vary by employer or instructor. • A common layout is: – Fields listed first – Methods listed second • Accessors and mutators are typically grouped. • There are tools that can help in formatting layout to specific standards. © 2012 Pearson Education, Inc. All rights reserved. 6-41
  • 42. Instance Fields and Methods • Fields and methods that are declared as previously shown are called instance fields and instance methods. • Objects created from a class each have their own copy of instance fields. • Instance methods are methods that are not declared with a special keyword, static. © 2012 Pearson Education, Inc. All rights reserved. 6-42
  • 43. Instance Fields and Methods • Instance fields and instance methods require an object to be created in order to be used. • See example: RoomAreas.java • Note that each room represented in this example can have different dimensions. Rectangle kitchen = new Rectangle(); Rectangle bedroom = new Rectangle(); Rectangle den = new Rectangle(); © 2012 Pearson Education, Inc. All rights reserved. 6-43
  • 44. States of Three Different Rectangle Objects The kitchen variable length: 10.0 holds the address of a address Rectangle Object. width: 14.0 The bedroom variable length: 15.0 holds the address of a address Rectangle Object. width: 12.0 The den variable length: 20.0 holds the address of a address Rectangle Object. width: 30.0 © 2012 Pearson Education, Inc. All rights reserved. 6-44
  • 45. Constructors • Classes can have special methods called constructors. • A constructor is a method that is automatically called when an object is created. • Constructors are used to perform operations at the time an object is created. • Constructors typically initialize instance fields and perform other object initialization tasks. © 2012 Pearson Education, Inc. All rights reserved. 6-45
  • 46. Constructors • Constructors have a few special properties that set them apart from normal methods. – Constructors have the same name as the class. – Constructors have no return type (not even void). – Constructors may not return any values. – Constructors are typically public. © 2012 Pearson Education, Inc. All rights reserved. 6-46
  • 47. Constructor for Rectangle Class /** Constructor @param len The length of the rectangle. @param w The width of the rectangle. */ public Rectangle(double len, double w) { length = len; width = w; } Examples: Rectangle.java, ConstructorDemo.java © 2012 Pearson Education, Inc. All rights reserved. 6-47
  • 48. Constructors in UML • In UML, the most common way constructors are defined is: Rectangle Notice there is no return type listed - width : double for constructors. - length : double +Rectangle(len:double, w:double) + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double © 2012 Pearson Education, Inc. All rights reserved. 6-48
  • 49. Uninitialized Local Reference Variables • Reference variables can be declared without being initialized. Rectangle box; • This statement does not create a Rectangle object, so it is an uninitialized local reference variable. • A local reference variable must reference an object before it can be used, otherwise a compiler error will occur. box = new Rectangle(7.0, 14.0); • box will now reference a Rectangle object of length 7.0 and width 14.0. © 2012 Pearson Education, Inc. All rights reserved. 6-49
  • 50. The Default Constructor • When an object is created, its constructor is always called. • If you do not write a constructor, Java provides one when the class is compiled. The constructor that Java provides is known as the default constructor. – It sets all of the object’s numeric fields to 0. – It sets all of the object’s boolean fields to false. – It sets all of the object’s reference variables to the special value null. © 2012 Pearson Education, Inc. All rights reserved. 6-50
  • 51. The Default Constructor • The default constructor is a constructor with no parameters, used to initialize an object in a default configuration. • The only time that Java provides a default constructor is when you do not write any constructor for a class. – See example: First version of Rectangle.java • A default constructor is not provided by Java if a constructor is already written. – See example: Rectangle.java with Constructor © 2012 Pearson Education, Inc. All rights reserved. 6-51
  • 52. Writing Your Own No-Arg Constructor • A constructor that does not accept arguments is known as a no-arg constructor. • The default constructor (provided by Java) is a no-arg constructor. • We can write our own no-arg constructor public Rectangle() { length = 1.0; width = 1.0; } © 2012 Pearson Education, Inc. All rights reserved. 6-52
  • 53. The String Class Constructor • One of the String class constructors accepts a string literal as an argument. • This string literal is used to initialize a String object. • For instance: String name = new String("Michael Long"); © 2012 Pearson Education, Inc. All rights reserved. 6-53
  • 54. The String Class Constructor • This creates a new reference variable name that points to a String object that represents the name “Michael Long” • Because they are used so often, String objects can be created with a shorthand: String name = "Michael Long"; © 2012 Pearson Education, Inc. All rights reserved. 6-54
  • 55. Overloading Methods and Constructors • Two or more methods in a class may have the same name as long as their parameter lists are different. • When this occurs, it is called method overloading. This also applies to constructors. • Method overloading is important because sometimes you need several different ways to perform the same operation. © 2012 Pearson Education, Inc. All rights reserved. 6-55
  • 56. Overloaded Method add public int add(int num1, int num2) { int sum = num1 + num2; return sum; } public String add (String str1, String str2) { String combined = str1 + str2; return combined; } © 2012 Pearson Education, Inc. All rights reserved. 6-56
  • 57. Method Signature and Binding • A method signature consists of the method’s name and the data types of the method’s parameters, in the order that they appear. The return type is not part of the signature. Signatures of the add(int, int) add methods of add(String, String) previous slide • The process of matching a method call with the correct method is known as binding. The compiler uses the method signature to determine which version of the overloaded method to bind the call to. © 2012 Pearson Education, Inc. All rights reserved. 6-57
  • 58. Rectangle Class Constructor Overload If we were to add the no-arg constructor we wrote previously to our Rectangle class in addition to the original constructor we wrote, what would happen when we execute the following calls? Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(5.0, 10.0); © 2012 Pearson Education, Inc. All rights reserved. 6-58
  • 59. Rectangle Class Constructor Overload If we were to add the no-arg constructor we wrote previously to our Rectangle class in addition to the original constructor we wrote, what would happen when we execute the following calls? Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(5.0, 10.0); The first call would use the no-arg constructor and box1 would have a length of 1.0 and width of 1.0. The second call would use the original constructor and box2 would have a length of 5.0 and a width of 10.0. © 2012 Pearson Education, Inc. All rights reserved. 6-59
  • 60. The BankAccount Example BankAccount.java BankAccount AccountTest.java -balance:double +BankAccount() Overloaded Constructors +BankAccount(startBalance:double) +BankAccount(strString): +deposit(amount:double):void Overloaded deposit methods +deposit(str:String):void +withdraw(amount:double):void Overloaded withdraw methods +withdraw(str:String):void +setBalance(b:double):void Overloaded setBalance methods +setBalance(str:String):void +getBalance():double © 2012 Pearson Education, Inc. All rights reserved. 6-60
  • 61. Scope of Instance Fields • Variables declared as instance fields in a class can be accessed by any instance method in the same class as the field. • If an instance field is declared with the public access specifier, it can also be accessed by code outside the class, as long as an instance of the class exists. © 2012 Pearson Education, Inc. All rights reserved. 6-61
  • 62. Shadowing • A parameter variable is, in effect, a local variable. • Within a method, variable names must be unique. • A method may have a local variable with the same name as an instance field. • This is called shadowing. • The local variable will hide the value of the instance field. • Shadowing is discouraged and local variable names should not be the same as instance field names. © 2012 Pearson Education, Inc. All rights reserved. 6-62
  • 63. Packages and import Statements • Classes in the Java API are organized into packages. • Explicit and Wildcard import statements – Explicit imports name a specific class • import java.util.Scanner; – Wildcard imports name a package, followed by an * • import java.util.*; • The java.lang package is automatically made available to any Java class. © 2012 Pearson Education, Inc. All rights reserved. 6-63
  • 64. Some Java Standard Packages © 2012 Pearson Education, Inc. All rights reserved. 6-64
  • 65. Object Oriented Design Finding Classes and Their Responsibilities • Finding the classes – Get written description of the problem domain – Identify all nouns, each is a potential class – Refine list to include only classes relevant to the problem • Identify the responsibilities – Things a class is responsible for knowing – Things a class is responsible for doing – Refine list to include only classes relevant to the problem © 2012 Pearson Education, Inc. All rights reserved. 6-65
  • 66. Object Oriented Design Finding Classes and Their Responsibilities – Identify the responsibilities • Things a class is responsible for knowing • Things a class is responsible for doing • Refine list to include only classes relevant to the problem © 2012 Pearson Education, Inc. All rights reserved. 6-66