Chapter 12 ObjectBased Programming 1 - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Chapter 12 ObjectBased Programming 1

Description:

For example, cars have state (current gear, number of seats, four wheels, etc. ... Third overloaded constructor has three int arguments ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 34
Provided by: susanw4
Category:

less

Transcript and Presenter's Notes

Title: Chapter 12 ObjectBased Programming 1


1
Chapter 12 Object-Based Programming 1
Introduction
  • What is Object Oriented Programming?
  • Object oriented Programming languages (OOP for
    short) include all the features of structured
    programming and add more powerful ways to
    organize algorithms and data structures.
  • There are three key features of OOP languages
  • Encapsulation
  • Inheritance
  • Polymorphism
  • All of them are tied to the notion of a class
  • These two lectures focus on encapsulation through
    the use of classes and objects - Object Based
    Programming.

2
Classes and Objects
  • A class defines a set of variables (data members)
    that can be associated with the methods which act
    on an object with the object itself.
  • An object is created through the instantiation of
    a class.
  • You can look around you now and see many examples
    of real-world objects your dog, your desk, your
    television set, your bicycle.
  • These real-world objects share two
    characteristics they all have state and they all
    have behavior. For example, cars have state
    (current gear, number of seats, four wheels,
    etc.) and behavior (braking, accelerating,
    slowing down, changing gears).

3
Classes
  • A class can be viewed as a blueprint of an
    object.
  • It is the model or pattern from which objects are
    created.
  • For example, the String class is used to define
    String objects.
  • Each String object contains specific characters
    (its state).
  • Each String object can perform services
    (behaviors) such as toUpperCase.

4
Classes
class TestStringClass public static void
main(String s) String s1 new
String("Programming") String s2 new
String("Java") String s3 new
String("ivet-ty") System.out.println(s1.toU
pperCase()) System.out.println(s2.toUpperCas
e()) System.out.println(s3.toUpperCase())

In this example, String is class. s1, s2 and s3
are the objects (or references to objects,
precisely speaking). Each of them has different
state but same behavior.
5
Classes and Objects
String (class)
  • The String class can be used to define as many
    String objects as you like.
  • Its reusability is very high.
  • The String class is provided for us by the Java
    standard class library.
  • But we can also write our own classes that define
    specific objects that we need

6
Classes
  • The following diagram explains the relationship
    between class and object.

7
Classes
  • A class contains data declarations and method
    declarations

int x, y char ch
Data declarations
Method declarations
8
Example
  • Let's define a very simple Employee class which
    has one data member and two methods.
  • class Employee
  • int empnum // data member (instance
    variable)
  • public int getNum() // method
  • return empnum
  • public void setNum(int newNum) // method
  • empnum newNum

9
Example
  • Thus when we create a new object we say we are
    instantiating the object. Each class exists only
    once in a program, but there can be many
    thousands of objects that are instances of that
    class.
  • To instantiate an object in Java we use the new
    operator. Here's how we'd create a new employee
  • Employee x new Employee()
  • The instantiation can also be done in two lines
  • Employee x
  • x new Employee()

10
Example
  • The members of an object are accessed using the .
    (dot) operator, as follows
  • Employee x new Employee()
  • x.setNum(12651)

11
Example
  • We define a test driver class to test the
    Employee class
  • class Employee
  • private int empnum
  • public int getNum()
  • return empnum
  • public void setNum(int newNum)
  • empnum newNum
  • class TestEmployee
  • public static void main(String args)
  • Employee emp1 new Employee()
  • Employee emp2 new Employee()
  • emp1.setNum(12651)
  • emp2.setNum(36595)
  • System.out.println("num of emp1 "
    emp1.getNum())
  • System.out.println("num of emp2 "
    emp2.getNum())

Sample Run gt java TestEmployee num of emp1
12651 num of emp2 36595
12
  • Note when you compile the file Employee.java, you
    get two class files
  • Employee.class and TestEmployee.class.
  • You can save the above program (two class
    definitions) into one source file.
  • But if both of them are public, they must be
    defined in separate files.
  • Every Java class must extend another class
  • If class does not explicitly extend another class
  • class implicitly extends Object
  • So class Employee extends java.lang.Object
  • is same as class Employee

13
Encapsulation
  • As you can see from the above diagram, an
    object's variables make up the centre or nucleus
    of the object. Methods surround and hide the
    object's nucleus from other objects in the
    program.
  • This is called encapsulation.

14
Encapsulation
  • Encapsulation is used to hide unimportant
    implementation details from other objects.
  • Thus, the implementation details can change at
    any time without affecting other parts of the
    program.
  • Benefits of Encapsulation
  • Modularity -- each object can be written and
    maintained independently of other objects. Also,
    an object can be easily passed around in the
    system.
  • Information hiding -- an object can maintain
    private information and methods that can be
    changed at any time without affecting the other
    objects that depend on it

15
A BAD Example
  • The following example shows an incorrect use of
    public data member.
  • class PublicDataEmployee
  • public int empnum
  • class PrintEmployee1
  • public static void main(String args)
  • PublicDataEmployee emp new
    PublicDataEmployee()
  • emp.empnum 12651
  • System.out.println("num of emp "
    emp.empnum)

gt java PrintEmployee1 num of emp 12651
16
A GOOD Example
  • The following shows how to fix the problem in the
    previous example.
  • class PrivateDataEmployee
  • private int empnum
  • public int getNum()
  • return empnum
  • public void setNum(int newNum)
  • empnum newNum
  • class PrintEmployee2
  • public static void main(String args)
  • PrivateDataEmployee emp new
    PrivateDataEmployee()
  • emp.setNum(12651)
  • System.out.println("num of emp "
    emp.getNum())

gt java PrintEmployee2 num of emp 12651
17
Why is PrivateDataEmployee better?
  • PublicDataEmployee is shorter than
    PrivateDataEmployee.
  • Why do we say PrivateDataEmployee is better?
  • Suppose the company wants to make the employee
    number more meaningful by dividing the employee
    number into two parts, deptID and staffID, and
    the employee number is obtained by the formula
    deptID1000 staffID.
  • e.g. If the IT Dept has department ID 13 and the
    staff ID of Paul Leung is 228, then his employee
    number is 13228.

18
  • Consider the class PublicDataEmployee, it needs
    to be changed to

class PublicDataEmployee2 public int
deptID public int staffID class
PrintEmployee3 public static void
main(String args) PublicDataEmployee2
emp new PublicDataEmployee2() emp.empnum
12651 System.out.println("num of emp "
emp.empnum)
  • PrintEmployee3 cannot be compiled anymore. You
    have to change every occurrence of emp.empnum in
    all programs that use PublicDataEmployee!!!!

19
  • The class PrivateDataEmployee can be modified to
    meet the new requirement easily.

gtjava PrintEmployee4 num of emp 12651
class PrivateDataEmployee2 private int
deptID private int staffID public int
getNum() return deptID1000staffID
public void setNum(int newNum)
deptID newNum/1000 staffID
newNum1000 class PrintEmployee4
public static void main(String args)
PublicDataEmployee emp new PublicDataEmployee()
emp.setNum(12651)
System.out.println("num of emp "
emp.getNum())
20
  • We only need to change PrivateDataEmployee2 and
    all other classes that depend on it (e.g.
    PrintEmployee4) does not need to change.
  • The use of private data with set and get methods
    can also protect the data from invalid
    modification.
  • e.g. To prevent setting of an employee number to
    a negative value, you can modify setNum as

public void setNum(int newNum) if (newNum lt
0) System.out.println("Invalid emp.
num.") else empnum newNum
21
Controlling Access to Members
  • Member access modifiers
  • Control access to class instance variables and
    methods
  • public
  • Variables and methods accessible to other classes
  • private
  • Variables and methods not accessible to other
    classes
  • Can be accessed via
  • Accessor method (get method)
  • Allow clients to read private data
  • Mutator method (set method)
  • Allow clients to modify private data

22
class PrivateDataEmployee3 private int
empnum public int getNum() return
empnum public void setNum(int newNum)
empnum newNum class
PrintEmployee5 public static void
main(String args) PrivateDataEmployee3
emp new PrivateDataEmployee3()
emp.empnum 12651
gtjavac PrivateDataEmployee3.java PrivateDataEmploy
ee3.java15 empnum has private access in
PrivateDataEmployee3 emp.empnum 12651
1 error
23
Data Scope (Revisited)
  • The scope of data is the area in a program in
    which that data can be used (referenced)
  • Data declared at the class level can be used by
    ALL methods in that class
  • Data declared within a method can ONLY be used in
    that method
  • Data declared within a method is called local data

24
Method Control Flow
  • The called method could be part of another class
    or object

25
Initializing Class Objects Constructors
  • Class constructor
  • Same name as class
  • No return type or return statement
  • Initializes instance variables of a class object
  • Cannot be called directly
  • Called when instantiating object of that class
  • If no constructor is defined by the programmer, a
    default "do-nothing" constructor is created for
    you.
  • Java does not provide a default constructor if
    the class define a constructor of its own.

26
Constructor Example
  • class Employee1
  • private int empnum
  • public Employee1(int newNum)
  • empnum newNum // call setNum is better,
    why?
  • public int getNum()
  • return empnum
  • public void setNum(int newNum)
  • empnum newNum
  • class PrintEmployee5
  • public static void main(String args)
  • Employee1 emp new Employee1(71623)
  • System.out.println(emp.getNum())

gtjava PrintEmployee5 71623
27
Using Overloaded Constructors
  • Overloaded constructors
  • Methods (in same class) may have same name
  • Must have different parameter lists
  • Examples in Java
  • String
  • JButton
  • .......

28
Time2.javaLines 16-19Default constructor has
no arguments Lines 23-26Overloaded constructor
has one int argument Lines 30-33Second
overloaded constructor has two int arguments
  • 1 // Fig. 8.6 Time2.java
  • 2 // Time2 class definition with overloaded
    constructors.
  • 3
  • 4
  • 5 // Java core packages
  • 6 import java.text.DecimalFormat
  • 7
  • 8 public class Time2
  • 9 private int hour // 0 - 23
  • 10 private int minute // 0 - 59
  • 11 private int second // 0 - 59
  • 12
  • 13 // Time2 constructor initializes each
    instance variable
  • 14 // to zero. Ensures that Time object
    starts in a
  • 15 // consistent state.
  • 16 public Time2()
  • 17
  • 18 setTime( 0, 0, 0 )
  • 19

29
Time2.javaLines 36-39Third overloaded
constructor has three int arguments Lines
42-45Fourth overloaded constructor has Time2
argument
  • 35 // Time2 constructor hour, minute and
    second supplied
  • 36 public Time2( int h, int m, int s )
  • 37
  • 38 setTime( h, m, s )
  • 39
  • 40
  • 41 // Time2 constructor another Time2
    object supplied
  • 42 public Time2( Time2 time )
  • 43
  • 44 setTime( time.hour, time.minute,
    time.second )
  • 45
  • 46
  • 47 // Set a new time value using universal
    time. Perform
  • 48 // validity checks on data. Set invalid
    values to zero.
  • 49 public void setTime( int h, int m, int s
    )
  • 50
  • 51 hour ( ( h gt 0 h lt 24 ) ? h 0
    )
  • 52 minute ( ( m gt 0 m lt 60 ) ? m
    0 )
  • 53 second ( ( s gt 0 s lt 60 ) ? s
    0 )

30
Time2.java
  • 70
  • 71 return ( (hour 12 hour 0) ?
    12 hour 12 )
  • 72 "" twoDigits.format( minute )
  • 73 "" twoDigits.format( second )
  • 74 ( hour lt 12 ? " AM" " PM" )
  • 75
  • 76
  • 77 // end class Time2

31
TimeTest4.java Line 15Declare six references
to Time2 objects Lines 17-22Instantiate each
Time2 reference using a different constructor
  • 1 // Fig. 8.7 TimeTest4.java
  • 2 // Using overloaded constructors
  • 3
  • 4 // Java extension packages
  • 5 import javax.swing.
  • 6
  • 7
  • 8
  • 9
  • 10 public class TimeTest4
  • 11
  • 12 // test constructors of class Time2
  • 13 public static void main( String args )
  • 14
  • 15 Time2 t1, t2, t3, t4, t5, t6
  • 16
  • 17 t1 new Time2() //
    000000
  • 18 t2 new Time2( 2 ) //
    020000
  • 19 t3 new Time2( 21, 34 ) //
    213400

32
TimeTest4.java
  • 34 output "\nt3 hour and minute
    specified "
  • 35 "second defaulted"
  • 36 "\n " t3.toUniversalString()
  • 37 "\n " t3.toString()
  • 38
  • 39 output "\nt4 hour, minute, and
    second specified"
  • 40 "\n " t4.toUniversalString()
  • 41 "\n " t4.toString()
  • 42
  • 43 output "\nt5 all invalid values
    specified"
  • 44 "\n " t5.toUniversalString()
  • 45 "\n " t5.toString()
  • 46
  • 47 output "\nt6 Time2 object t4
    specified"
  • 48 "\n " t6.toUniversalString()
  • 49 "\n " t6.toString()
  • 50
  • 51 JOptionPane.showMessageDialog( null,
    output,
  • 52 "Demonstrating Overloaded
    Constructors",

33
TimeTest4.javaDifferent outputs, because each
Time2 reference was instantiated with a different
constructor
Different outputs, because each Time2 reference
was instantiated with a different constructor
Write a Comment
User Comments (0)
About PowerShow.com