Chapter 2: Java and Object Orientiation - PowerPoint PPT Presentation

1 / 107
About This Presentation
Title:

Chapter 2: Java and Object Orientiation

Description:

Abstraction. Code as a 'black box' that you have the means to externally control. Use something without knowing how it works. Procedural ... Data Abstraction ... – PowerPoint PPT presentation

Number of Views:217
Avg rating:3.0/5.0
Slides: 108
Provided by: TimothyCL4
Category:

less

Transcript and Presenter's Notes

Title: Chapter 2: Java and Object Orientiation


1
Chapter 2 Java and Object Orientiation
  • Motivation
  • Abstraction.
  • Code as a black box that you have the means to
    externally control. Use something without
    knowing how it works.
  • Procedural Abstraction
  • You dont need to worry about the details of how
    some operation is performed, just what the inputs
    and outputs are
  • Data Abstraction
  • Grouping together (modeling) data that represents
    some entity so you can programmatically treat it
    as a single unit.
  • Effectively you are building and using black
    box models to be able to handle increasingly
    complex operations with increasingly complex
    data.

2
Lesson Object-Oriented Programming Concepts
  • What is an Object?
  • An object has state and behavior.
  • What is a Class
  • A class is a blueprint from which objects are
    created.
  • What is Inheritance?
  • Inheritance provides a powerful and natural
    mechanism for organizing and structuring your
    software.
  • What is an Interface?
  • An interface is a contract between a class and
    the outside world.
  • What is a Package?
  • A package is a namespace for organizing classes
    and interfaces in a logical manner.

3
What Is an Object? Real-World Objects
  • Object Oriented Technology views software in the
    same way we view real-world objects.
  • Real-world objects share two characteristics
  • They all have state and behavior.
  • Examples of real-world objects
  • Dogs have state (name, color, breed, hungry) and
    behavior (barking, fetching, wagging tail).
  • Bicycles have state (current gear, current pedal
    cadence, current speed) and behavior (changing
    gear, changing pedal cadence, applying brakes).
  • Desktop radio has states (on, off, current
    volume, current station) and behavior (turn on,
    turn off, increase volume, decrease volume, seek,
    scan, and tune).
  • You may also notice that some objects, in turn,
    will also contain other objects

4
What Is an Object? Software Objects
  • Software objects consist of state and related
    behavior.
  • An object stores its state in fields (variables).
  • exposes its behavior through methods (functions).
  • Methods
  • operate on an objects internal state.
  • serve as the primary mechanism for
    object-to-object communication.
  • Data Encapsulation
  • Hiding internal state and requiring all
    interaction to be performed through an objects
    methods is known as data encapsulation a
    fundamental principle of object-oriented
    programming.

5
What Is an Object? A Software Object
Representation of a Bicycle
  • Software objects consist of state and related
    behavior.
  • An object stores its state in fields (variables).
  • Shows its behavior through methods (functions).
  • Methods
  • Operate on an objects internal state.
  • Serve as the primary mechanism for
    object-to-object communication.

By attributing state (current speed, current
pedal cadence, and current gear) and providing
methods for changing that state, the object
remains in control of how the outside world is
allowed to use it. For example, if the bicycle
only has 6 gears, a method to change gears could
reject any value that is less than 1 or greater
than 6.
6
Benefits of Object Orientation
  • Modularity
  • The source code for an object can be written and
    maintained independently of the source code for
    other objects.
  • Once written, the source code for an object can
    be easily passed around inside the system.
  • Information-hiding
  • By interacting only with an objects methods, the
    details of its internal implementation remain
    hidden from the outside world.
  • Reduces complexity.
  • The details of its internal implementation can be
    changed without affecting other objects that use
    it.

7
Benefits of Object Orientation
  • Code re-use
  • A fundamental principle of software engineering
    is basing software development of re-usable
    technology.
  • Reusing already tested/debugged objects leads to
    higher quality software.
  • Pluggability and debugging ease
  • If a particular object turns out to be
    problematic, you can simply remove it from your
    application and plug in a different object as its
    replacement.
  • EXIf a bolt breaks, you replace it, not the
    entire machine.

8
What is a Class?
  • In the real world, youll often find many
    individual objects all of the same kind.
  • There may be thousands of other bicycles in
    existence, all of the same make and model.
  • Each bicycle was built from the same set of
    blueprints and therefore contains the same
    components.
  • In object-oriented terms, we say that your
    bicycle is an instance of the class of objects
    known as bicycles.
  • A class is the blueprint from which individual
    objects are created.

9
What is a Class? E.g. Bicycle Class
  • class Bicycle
  • int cadence 0
  • int speed 0
  • int gear 1
  • void changeCadence(int newValue)
  • cadence newValue
  • void changeGear(int newValue)
  • gear newValue
  • void speedUp(int increment)
  • speed speed increment

10
Bicycle Class Declaration
  • class Bicycle
  • int cadence 0
  • int speed 0
  • int gear 1
  • void changeCadence(int newValue)
  • cadence newValue
  • void changeGear(int newValue)
  • gear newValue
  • void speedUp(int increment)
  • speed speed increment

11
Bicycle Class Fields State
  • class Bicycle
  • int cadence 0
  • int speed 0
  • int gear 1
  • void changeCadence(int newValue)
  • cadence newValue
  • void changeGear(int newValue)
  • gear newValue
  • void speedUp(int increment)
  • speed speed increment

12
Bicycle Class Methods Behavior
  • class Bicycle
  • int cadence 0
  • int speed 0
  • int gear 1
  • void changeCadence(int newValue)
  • cadence newValue
  • void changeGear(int newValue)
  • gear newValue
  • void speedUp(int increment)
  • speed speed increment

13
Bicycle Demo Class
  • class BicycleDemo
  • public static void main(String args)
  • // Create two different Bicycle objects
  • Bicycle bike1 new Bicycle()
  • Bicycle bike2 new Bicycle()
  • // Invoke methods on those objects
  • bike1.changeCadence(50)
  • bike1.speedUp(10)
  • bike2.changeCadence(50)

14
UML Representation of Class
Name of class
Bicycle
List of Fields
gear speed
changeGear speedUp
List of Methods
15
UML Classes and Association
BicycleDemo has a reference to Bicycle (indicated
by the arrow).
Bicycle
BicycleDemo
gear speed
main()
changeGear speedUp
Bicycle does NOT have a reference to BicycleDemo
(indicated by the lack of an arrow)
16
UML Sequence Diagram Example Objective to show
how BicycleDemo creates and sends messages to
Bicycle objects.
17
Creating Objects
  • A class provides the blueprint for objects.
  • You create an object from a class. For example,
    the following statement consists of three parts
  • Point myPoint new Point(23, 94)
  • Declaration of the reference variable. myPoint is
    declared as a Point.
  • Initialization of the object. Points constructor
    is called to initialize the object.
  • Instantiation of the class. Javas new operator
    creates the object.

18
Declaration of the Reference Variable
  • Usually, the reference variable is declared in
    the same statement with the new operator, e.g
  • Point myPoint new Point(23, 94)
  • Sometimes, declaration of a reference variable is
    required without intializing it, i.e., without
    assigning an object to it., e.g
  • Point myPoint
  • For example, later on in a program
  • myPoint aPoint //aPoint refers to a
    previously created object.

19
Declaring a Variable to Refer to an Objecttype
name
  • A variable declaration (type name) notifies the
    compiler that you will use name to refer to data
    whose type is type.
  • A reference variable declaration does not reserve
    memory for the object to which the reference
    refers.
  • A reference variable declaration does not create
    an object.

20
Declaring a Variable to Refer to an Objecttype
name
  • For example, when originOne is declared
  • Point originOne
  • Memory for the pointer (originOne) is reserved,
    but
  • No memory for an object of type Point is
    reserved.
  • The pointers memory is initialized to null,
    i.e., originOne points to nothing initially.

21
Note Declaring a Primitive Variable(difference
between object and primitive variable
declarations)
  • A primitive variable declaration reserves memory
    for the variable. For example, consider byte,
    short, and int

byte x
short x
int x
. . .
. . .
. . .
x
x
x
. . .
. . .
. . .
22
Instantiating a Class
  • The new operator instantiates a class by
    allocating memory for a new object and returning
    a reference to that memory.
  • The new operator also invokes the object
    constructor.
  • Note The phrase instantiating a class means
    the same thing as creating an object. When you
    create an object, you are creating an instance
    of a class, therefore instantiating a class.
  • The new operator requires a single, postfix
    argument a call to a constructor. The name of
    the constructor provides the name of the class to
    instantiate.

23
Instantiating a Class
  • The new operator returns a reference to the
    object it created. This reference is usually
    assigned to a variable of the appropriate type,
    like
  • Point originOne new Point(23, 94)
  • The reference returned by the new operator does
    not have to be assigned to a variable. It can
    also be used directly in an expression. For
    example
  • int height new Rectangle().height

24
Initializing an Object Single Constructor
  • public class Point
  • public int x 0
  • public int y 0
  • //constructor
  • public Point(int a, int b)
  • x a
  • y b
  • This class contains a single constructor. You can
    recognize a constructor because its declaration
    uses the same name as the class and it has no
    return type. The constructor in the Point class
    takes two integer arguments, as declared by the
    code (int a, int b).

25
Constructing and Initializing an Object
  • Point originOne new Point(23, 94)

26
Multiple Constructors
  • A class can have multiple constructors.
  • Each constructor lets you provide different type
    or number of arguments, as required by the class.
  • If a class has multiple constructors, they must
    have different signatures.
  • The Java compiler differentiates the constructors
    based on the number and the type of the arguments.

27
Multiple Constructors
  • public class Rectangle
  • private int width 0
  • private int height 0
  • private Point origin
  • // two constructors
  • public Rectangle()
  • origin new Point(0, 0)
  • public Rectangle(Point p, int w, int h)
  • origin p
  • width w
  • height h

28
Example Multiple ReferencesAn Object Within an
Object
Creates a Point Object.
  • Point originOne new Point(23, 94)
  • Rectangle rectOne new Rectangle(originOne, 100,
    200)

Rectangle has multiple constructors. This one
requires specification of the origin, width, and
height.
  • originOne refers to the point Object.
  • originOne is used as an argument in the Rectangle
    constructor to initialize the origin of the newly
    created Rectangle Object.
  • The constructor also initializes width and height.

29
No-Argument Constructor
  • The Rectangle constructor used in the following
    statement doesnt take any arguments, so its
    called a no-argument constructor
  • Rectangle rect new Rectangle()
  • All classes have at least one constructor.

30
No Constructor
  • If a class does not explicitly declare a
    constructor, the Java compiler automatically
    provides a no-argument constructor, called the
    default constructor.
  • This default constructor calls the class parents
    no-argument constructor, or the Object
    constructor if the class has no other parent.
  • If the parent has no constructor (Object does
    have one), the compiler will reject the program.

31
Referencing an Objects Fields Simple Names
  • Consider an object created from a given class
  • This object can use simple names to refer to its
    own instance fields.
  • For example, consider the following print
    statement executed from within an instance method
    of an object of type Rectangle (width and height
    are instance variables.)
  • System.out.println("Width and height are
  • " width ", " height)
  • In this case, the width and height are referred
    to by their simple names, width and height.

32
Referencing an Objects Fields dot (.) operator
Names
  • Code that is outside the objects class must use
    an (1) object reference or (2) expression,
    followed by the dot (.) operator, followed by a
    simple field name.
  • An object reference
  • aVariable objectReference.fieldName
  • Eg myWidth someRectangle.width
  • An expression
  • int height new Rectangle().height
  • Note no reference for the object is stored, and
    as such, the new object is subject to javas
    recycler.

33
Referencing an Objects Field Incorrectly
  • public class CreateObjectDemo
  • public static void main(String args)
  • System.out.println("Width of rectOne "
    width)
  • public class Rectangle
  • public int width 0
  • public int height 0
  • Using the simple name width here doesnt make
    sense.
  • The instance field width exists only within an
    object.
  • results in a compiler error.

34
Referencing an Objects Fields Proper Usage of
the dot (.) operator Name
  • public class CreateObjectDemo
  • public static void main(String args)
  • Rectangle rectOne new Rectangle(originOne,
    100, 200)
  • System.out.println("Width of rectOne "
    rectOne.width)
  • public class Rectangle
  • public int width 0
  • public int height 0
  • public Rectangle()
  • origin new Point(0, 0)
  • a Rectangle object is created.
  • The .dot operator name is used to reference the
    Objects instance field.

35
Invoking an Objects Own Methods Simple Names
  • Consider an object created from a given class
  • This object can use simple names to invoke its
    own methods.
  • For example, consider a Rectangle class, (next
    slide)
  • Since setHeight()sets the height of the
    rectangle, it should also update the area
    instance variable.
  • setHeight()updates the area variable by calling
    the getArea() method using the simple name
    getArea().

36
Invoking an Objects Own Methods Simple Names
Assume the myRectangle object exists. Then assume
some code calls the setHeight() and setWidth()
(not shown) methods of the myRectangle object.
  • public class Rectangle
  • private int width, height, area
  • //put constructor here.
  • public void setHeight(int h)
  • height h
  • area getArea()
  • public int getArea()
  • return heightwidth

setHeight()updates the area field by calling the
getArea()method using the simple name getArea().
37
Invoking an External-Objects Methods
  • An object reference is used to invoke (call) an
    external-objects method.
  • Append the methods simple name to the object
    reference, with an intervening dot operator (.).
  • Provide, within enclosing parentheses, any
    arguments to the method.
  • If the method does not require any arguments, use
    empty parentheses.
  • objectReference.methodName(argumentList)
  • or
  • objectReference.methodName()

38
Invoking an External-Objects Methods
  • objectReference.methodName(argumentList)
  • The objectReference must be a reference to an
    object.
  • You can use a variable name that has been
    previously assigned to the target object.
  • You also can use any expression that returns an
    object reference.

39
Invoking an External-Objects Objects
MethodsExamples
  • new Rectangle(100, 50).getArea()
  • int areaOfRectangle new Rectangle(100,
    50).getArea()

getArea() of the created object returns a
variable of type int, which is assigned to
areaOfRectangle.
40
The Garbage Collector
  • Some object-oriented languages require that you
    keep track of all the objects you create and that
    you explicitly destroy them when they are no
    longer needed. Managing memory explicitly is
    tedious and error-prone.
  • The Java platform allows you to create as many
    objects as you want (limited, of course, by what
    your system can handle), and you dont have to
    worry about destroying them.
  • The Java runtime environment deletes objects when
    it determines that they are no longer being used.
    This process is called garbage collection.
  • An object is eligible for garbage collection when
    there are no more references to that object.
  • Dropped when a reference goes out of scope.
  • Dropped when a reference is set to null.
  • The Java runtime environment has a garbage
    collector that periodically frees the memory used
    by objects that are no longer referenced. The
    garbage collector does its job automatically when
    it determines that the time is right.

41
Notes on Overloaded Methods
  • When there are two or more methods (including
    constructors) with the same name declared in a
    class the methods are said to be overloaded.
  • Overloaded methods are differentiated by the
    number and the type of the arguments passed into
    the method.
  • You cannot declare more than one method with the
    same name and the same number and type of
    arguments, because the compiler cannot tell them
    apart.
  • The compiler does not consider return type when
    differentiating methods, so you cannot declare
    two methods with the same signature even if they
    have a different return type.

42
What Is Inheritance?
  • Different kinds of objects often have a certain
    amount in common with each other.
  • Mountain bikes, road bikes, and tandem bikes, for
    example, all share the characteristics of
    bicycles (current speed, current pedal cadence,
    current gear).
  • Yet each also defines additional features that
    make them different
  • tandem bicycles have two seats and two sets of
    handlebars
  • road bikes have drop handlebars
  • some mountain bikes have an additional chain
    ring, giving them a lower gear ratio.

43
What Is Inheritance?
  • Object-oriented programming allows classes to
    inherit commonly used state and behavior from
    other classes.
  • For example, Bicycle now becomes the superclass
    of MountainBike, RoadBike, and TandemBike.

44
Inheritance
  • A class that is derived from another class is
    called a subclass (also a derived class, extended
    class, or child class).
  • The class from which the subclass is derived is
    called a superclass (also a base class or a
    parent class).
  • Excepting Object, which has no superclass, every
    class has one and only one direct superclass
    (single inheritance).

45
What You Can Do in a Subclass
  • A subclass inherits all of the public and
    protected members of its parent, no matter what
    package the subclass is in.
  • If the subclass is in the same package as its
    parent, it also inherits the package-private
    members of the parent.
  • You can use the inherited members as is, replace
    them, hide them, or supplement them with new
    members.

46
Inheritance Syntax
  • At the beginning of your class declaration, use
    the extends keyword, followed by the name of the
    class to inherit from
  • class MountainBike extends Bicycle
  • // new fields and methods defining a
  • // mountain bike would go here, e.g.
  • This gives MountainBike all the same fields and
    methods as Bicycle, yet allows its code to focus
    exclusively on the features that make
    MountainBike unique.

47
Inheritance Example
  • class MountainBike extends Bicycle
  • int seatHeight
  • public void setHeight(int newValue)
  • seatHeight newValue
  • MountainBike inherits all the fields and methods
    of Bicycle and adds the field seatHeight and a
    method to set it (mountain bikes have seats that
    can be moved up and down as the terrain demands).

48
UML Representation of Inheritance
Superclass
Closed, non-filled, solid line triangle points to
the superclass
49
Inheritance Rules
  • Java programming language specific rules
  • each class is allowed to have a maximum of one
    direct superclass.
  • each superclass has the potential for an
    unlimited number of subclasses.
  • Good Object Oriented practise rules
  • Ensure each subclass obeys the ISA rule
  • Distinctiveness rule
  • Make sure all inherited features make sense in
    each sublcass

50
Inheritance Rules ISA Rule
  • Ensure each subclass obeys the ISA rule
  • A chequing account is an account.
  • A village is a municipality.
  • A mountain bike is a bike.
  • Should Province be a subclass of Country?
  • No, a Province is not a Country.
  • Modeling a Province as a Country violates the ISA
    rule.
  • Modeling a Province as Country would artificially
    introduce complexity into the source code, making
    the source code more difficult to understand,
    maintain, and use.

51
Inheritance Rules Distinctiveness Rule
  • A subclass must retain its distinctiveness
    throughout its life.
  • Consider a bike with training wheels, for
    teaching kids to ride.
  • You might consider creating a class called
    TrainingBicycle, and making this a subclass of
    Bicycle.
  • However, a training wheel bicycle will not be a
    training bike once the training wheels are
    removed.
  • Therefore, TrainingBicycle is not a subclass of
    Bicycle.
  • Modeling a TrainingBicycle as a Bicycle would
    artificially introduce complexity into the source
    code, making the source code more difficult to
    understand, maintain, and use.
  • Actually, TrainingBicycle should not even be a
    class.
  • Its better to have a field that indicates if a
    Bicycle has training wheels.

52
Inheritance Rules MSFMS
  • Make sure that each feature of a superclass makes
    sense in each subclass.
  • Each subclass inherits the features of a
    superclass.
  • Modeling a class as a subclass of some superclass
    with one or more features that do not make sense
    in the subclass would artificially introduce
    complexity into the source code, making the
    source code more difficult to understand,
    maintain, and use.

53
What Is a Package?
  • A package is a container in which related classes
    and interfaces are grouped together.
  • Conceptually you can think of packages as being
    similar to different folders on your computer.
  • You might keep HTML pages in one folder, images
    in another, and scripts or applications in yet
    another.
  • For large programs which are composed of hundreds
    or thousands of individual classes, it makes
    sense to keep things organized by placing related
    classes and interfaces into packages.

54
Reasons for Using Packages
  • You and other programmers can easily determine
    that these types are related.
  • You and other programmers know where to find
    types that can provide related functions.
  • The names of your types wont conflict with the
    type names in other packages because the package
    creates a new namespace.
  • You can allow types within the package to have
    unrestricted access to one another yet still
    restrict access for types outside the package.

55
Creating a Package
  • To create a package
  • Choose a name for the package.
  • Put a package statement at the top of every
    source file that you want to include in the
    package.
  • A source file may contain one of the types
  • classes, interfaces, enumerations, and annotation
  • The package statement must be the first line in
    the source file. For example,
  • package graphics
  • There can be only one package statement in each
    source file, and it applies to all types in the
    file.

56
Storing Types in Source Files
  • Usually, you will store one type per source file,
    and you will name the file generally
    NameOfType.java, for instance
  • public class Circle in the file Circle.java
  • public interface Draggable in the file
    Draggable.java
  • If you put multiple types in a single source
    file, only one can be public, and it must have
    the same name as the source file.
  • You can include non-public types in the same file
    that contains a public type.
  • This is strongly discouraged, unless the
    non-public types are small and closely related to
    the public type.

57
Using Package Members
  • The types that comprise a package are known as
    the package members.
  • To use a public package member from outside its
    package, either
  • Refer to the member by its fully qualified name.
  • Import the package member.
  • Import the member's entire package.
  • Each is appropriate for different situations.

58
Referring to a Package Member by Its Qualified
Name
  • You can use a package members simple name if the
    code you are writing is in the same package as
    that member or if that member has been imported.
  • Rectangle myRect new Rectangle()
  • However, if you are trying to use a member from a
    different package and that package has not been
    imported
  • you must use the members fully qualified name,
    which includes the package name. For example,
  • graphics.Rectangle myRect new
    graphics.Rectangle()

59
Referring to a Package Member by Its Qualified
Name
  • Using qualified names are okay for infrequent
    use.
  • When a name is used repetitively, however, typing
    the name repeatedly becomes tedious and the code
    becomes difficult to read.
  • As an alternative, you can import the member or
    its package and then use its simple name.

60
Importing a Package Member
  • To import a specific (i.e., one) member into the
    current file
  • Put an import statement at the beginning of the
    file
  • Before any type definitions
  • But after the package statement, if there is one.
  • Example Conisder a Circle class that is a member
    of the graphics.ellipse package. The Circle class
    needs access to the Rectangle class, which is
    located in the graphics.polygon package
  • package graphics.ellipse
  • import graphics.polygon.Rectangle

The first two lines the file Circle.java
61
Importing a Package Member
  • Now, the class Circle, you can refer to the
    Rectangle class by its simple name.
  • Rectangle myRectangle new Rectangle()
  • This approach works well if you use just a few
    members from the graphics package.
  • But if you want to use many members from a
    package, you should import the entire package.

62
Importing an Entire Package
  • To import all the types contained in a particular
    package, use the import statement with the
    asterisk () wildcard character.
  • import graphics.polygon.
  • Now you can refer to any class or interface in
    the graphics.polygon package by its simple name.
  • RegularPolygon regPolygon new RegularPolygon()
  • Rectangle myRectangle new Rectangle()

63
Importing an Entire Package
  • The asterisk in the import statement can be used
    only to specify all the classes within a package.
  • It cannot be used to match a subset of the
    classes in a package.
  • For example, the following does not match all the
    classes in the graphics package that begin with
    A.
  • import graphics.A //does not work
  • Generates a compiler error.
  • With the import statement, you generally import
    only a single package member or an entire
    package.

64
Importing an Entire Package
  • For convenience, the Java compiler automatically
    imports three entire packages for each source
    file
  • the package with no name,
  • the java.lang package, and
  • the current package (the package for the current
    file).

Files in a folder (directory) that do not have a
package statement belong to the no-name package.
All of those files are imported.
If you compile a file that has a package
statement, then all of the members of the package
are imported.
65
Apparent Hierarchies of Packages
  • Importing packages is not hierarchical
  • import java.awt. does not include
  • java.awt.color
  • java.awt.font
  • If you plan to use the classes and other types in
    java.awt.color as well as those in java.awt, you
    must import both packages with all their files
  • import java.awt.
  • import java.awt.color.

66
Name Ambiguities
  • If a member in one package shares its name with a
    member in another package and both packages are
    imported,
  • Simple names cannot be used.
  • You must refer to each member by its qualified
    name.
  • graphics.Rectangle rect1
  • java.awt.Rectangle rect2

67
Using the this Keyword
  • Within an Object, sometimes using a simple name
    is not possible (see next slide).
  • In this case an object reference is required in
    order to use the .dot operator.
  • Within an instance method or a constructor, the
    keyword this is a reference to the current
    object.
  • The keyword this refers to the object whose
    method or constructor is being executed.
  • You can refer to any member of the current object
    from within an instance method or a constructor
    by using this .

68
Using this To Un-Shadow a Field
  • The most common reason for using the this keyword
    is because a field is shadowed by a method or
    constructor parameter.

Not Shadowing
public class Point public int x 0 public
int y 0 public Point(int a, int b) x
a y b
  • Each argument in the constructor shadows one of
    the objects fields.
  • Inside the constructor, x is a local copy of the
    constructors first argument.
  • To refer to the Point field x, the constructor
    must use this.x

69
Using this with a Constructor
  • From within a constructor, you can also use the
    this keyword to call another constructor in the
    same class. This is called an explicit
    constructor invocation.
  • public class Rectangle
  • private int x, y
  • private int width, height
  • public Rectangle()
  • this(0, 0, 0, 0)
  • public Rectangle(int x, int y, int width, int
    height)
  • this.x x
  • this.y y
  • this.width width
  • this.height height

70
Controlling Access to Members of a Class
  • Access level modifiers determine whether other
    classes can use a particular field or invoke a
    particular method. There are two levels
  • Class level (top level)
  • public, or package-private (no explicit
    modifier).
  • Member of a class level
  • public, private, protected, or package-private
    (no explicit modifier).

71
Controlling Access to Members of a Class
  • If you declare a class with the modifier public
  • That class is visible to all classes everywhere
    in the application (World).
  • If you declare a class with no modifier
  • This is the default, also known as
    package-private
  • If a class is declared with the modifier
    package-private
  • Then it is visible only within its own package.

72
Controlling Access to Members of a Class
  • If you declare a member of a class with the
    modifier private
  • That member can only be accessed in its own
    class.
  • A subclass does not inherit the private members
    of its parent class.
  • However, if the superclass has public or
    protected methods for accessing its private
    fields, these can also be used by the subclass.
  • If you declare a member of a class with the
    modifier protected
  • That member can only be accessed within its own
    package (as with package-private) and, in
    addition, by a subclass of its class in another
    package.

73
Controlling Access to Members of a Class
  • Modifier Class Package Subclass World
  • public Y Y Y Y
  • protected Y Y Y N
  • no modifier Y Y N N
  • private Y N N N
  • The Class column indicates whether the class
    itself has access to its own members, which have
    the indicated modifier (access level).
  • The Package column indicates whether classes in
    the same package as the class (regardless of
    their parentage) have access to the member.
  • The Subclass column indicates whether
    subclasses of the class declared outside this
    package have access to the member.
  • The World column indicates whether all classes
    have access to the member.

74
Tips on Choosing an Access Level
  • If other programmers use your class, you want to
    ensure that errors from misuse cannot happen.
    Access levels can help you do this.
  • Use the most restrictive access level that makes
    sense for a particular member.
  • Use private unless you have a good reason not to.
  • Avoid public fields except for constants.
  • Many of the examples in the tutorial use public
    fields. This may help to illustrate some points
    concisely, but is not recommended for production
    code.
  • Public fields tend to make your code
    un-re-usable.

75
Understanding Instance and Class Members
  • In this section, we discuss the use of the static
    keyword to create fields and methods that belong
    to the class, rather than to an instance of the
    class.

76
Recall Instance Variables
  • When a number of objects are created from the
    same class blueprint, they each have their own
    distinct copies of instance variables.
  • In the case of the Bicycle class, the instance
    variables are cadence, gear, and speed. Each
    Bicycle object has its own values for these
    variables, stored in different memory locations.

77
Class Variables
  • Sometimes, you want to have variables that are
    common to all objects. This is accomplished with
    the static modifier.
  • Fields that have the static modifier in their
    declaration are called static fields or class
    variables.
  • Class variables are associated with the class,
    rather than with any object.

78
Class Variables
  • Every instance of the class shares a class
    variable.
  • A class variable is stored in one fixed location
    in memory.
  • Any object can change the value of a class
    variable, but class variables can also be
    manipulated without creating an instance of the
    class.
  • Class variables are referenced by the class name
    itself, as in
  • Bicycle.numberOfBicycles
  • This makes it clear that they are class
    variables.

79
Invoking Class Methods
  • The Java programming language supports static
    methods as well as static variables.
  • Static methods, which have the static modifier in
    their declarations, are invoked with the class
    name, without the need for creating an instance
    of the class, as in
  • ClassName.methodName(args)

80
Creating Class Methods
  • A common use for static methods is to access
    static fields.
  • For example, we could add a static method to the
    Bicycle class to access the numberOfBicycles
    static field
  • public static int getNumberOfBicycles()
  • return numberOfBicycles
  • Code might call this static method as follows
  • numBikes Bicycle.getNumberOfBicycles()

81
Comprehension Exercise
  • Instance methods can access instance variables
    and instance methods by using either
  • simpleName or objectReference.simpleName.
  • Instance methods can access class variables and
    class methods by using
  • ClassName.simpleName.
  • Class methods can access class variables and
    class methods by using
  • ClassName.simpleName.
  • Class methods cannot access instance variables or
    instance methods directlythey must use an object
    reference. Also, class methods cannot use the
    this keyword as there is no instance for this to
    refer to.

82
Constants
  • The static modifier, in combination with the
    final modifier, is also used to define constants.
  • The final modifier indicates that the value of
    this field cannot change.
  • For example, static final double PI
    3.1415926535
  • Constants defined in this way cannot be
    reassigned, and it is a compile-time error if
    your program tries to do so.
  • By convention, the name of constant values are
    spelled in uppercase letters.
  • If the name is composed of more than one word,
    the words are separated by an underscore (_).

83
Initializing A Static Field
  • In its declaration.
  • public static int capacity 10
  • This works well when the initialization value is
    available and the initialization can be put on
    one line.
  • In a static initialization block.
  • static
  • // Whatever code is needed for
    initialization
  • // goes here.
  • A class can have any number of static
    initialization blocks, and they can appear
    anywhere in the class body. The runtime system
    guarantees that static initialization blocks are
    called in the order that they appear in the
    source code.

84
Initializing A Static Field
  • In a private static method.
  • class Whatever
  • public static varType myVar
    initializeClassVariable()
  • private static varType initializeClassVariable()
  • //initialization code goes here
  • The advantage of private static methods is that
    they can be reused later if you need to
    reinitialize the class variable.

85
Initializing Instance Fields
  • In its declaration.
  • private boolean full false
  • It makes more sense to initialize an instance
    field in a constructor.
  • However, more complex initialization may be
    required.
  • In this case, use an an initialization block
  • //Whatever code is needed for
  • //initialization goes here.
  • The Java compiler copies initializer blocks into
    every constructor.
  • This is useful particularly if every constructor
    requires the same initialization block.

86
Overriding Instance Methods
  • Sometimes, when you need certain behavior in your
    application, instead of developing a new class,
    you might be able to find (re-use) another class
    whose behavior is close enough to the desired
    behavior.
  • In this case, you can get the behavior of the
    other class by declaring one of your classes to
    be a subclass, thus inheriting the behavior.
  • But, you might need to modify the behavior
    slightly.
  • You can modify the behavior of an inherited
    instance method by
  • Declaring an instance method in a subclass with
    the same signature (name, plus the number and the
    type of its parameters) and return type as an
    instance method in the superclass.
  • You define the modified behavior in the instance
    method in the subclass.
  • The instance method in the subclass overrides the
    superclasss method.

87
Inheritance Example with No-Overriding
  • public class Animal
  • public void testInstanceMethod()
  • System.out.println("The instance method in
    Animal.")
  • public class Cat extends Animal
  • public static void main(String args)
  • Cat myCat new Cat()
  • myCat.testInstanceMethod()

The myCat object inherits the instance method,
testInstanceMethod().
The testInstanceMethod() defined in Animal is
invoked.
88
Inheritance Example with Overriding
The overriden testInstanceMethod().
  • public class Animal
  • public void testInstanceMethod()
  • System.out.println("The instance method in
    Animal.")
  • public class Cat extends Animal
  • public void testInstanceMethod()
  • System.out.println("The instance method in
    Cat.")
  • public static void main(String args)
  • Cat myCat new Cat()
  • myCat.testInstanceMethod()

This method (called the overriding method)
overrides the superclass version.
The testInstanceMethod() defined in Cat is
invoked.
89
Overriding Rules
  • For restriction
  • E.g. a general scale(x,y) method for graphical
    objects would not work in Circle
  • The overriding method would need to restrict x
    y.
  • For extension
  • E.g. SavingsAccount might charge an extra fee
    following every debit.
  • For optimization
  • E.g. The getBoundingRect method in Rectangle is
    much simpler than the one in Polygon.

90
Hiding Class Methods
  • Normally, a subclass inherits the class methods
    of the superclass.
  • If a subclass defines a class method with the
    same signature as a class method in the
    superclass, the method in the subclass is said to
    hide the one in the superclass.
  • The version of the hidden method that gets
    invoked depends on whether it is invoked from the
    superclass or the subclass.

91
Inheritance Example with Hidding
The hidden testClassMethod().
  • public class Animal
  • public static void testClassMethod()
  • System.out.println("The class method in
    Animal.")
  • public class Cat extends Animal
  • public static void testClassMethod()
  • System.out.println("The class method in
    Cat.")
  • public static void main(String args)
  • Animal.testClassMethod()
  • Cat.testClassMethod()

This method hides the superclass version.
The testClassMethod() defined in Animal is
invoked.
The testClassMethod() defined in Cat is invoked.
92
The Distinction Between Hiding And Overriding
  • A subclass overrides a method in a superclass
  • Normally, a subclass object will not need to
    access the overriden method, because there was a
    need to override it in the first place.
  • Subclass objects cannot simply access the
    overridden method in the superclass.
  • In cases where access is required, the subclass
    object can use the super keyword to access the
    overridden method in the superclass.
  • A subclass hides a method in a superclass
  • Subclass objects can access either the superclass
    method or the subclass method depending on the
    reference used.

93
Using the Keyword super
  • Accessing Superclass Members
  • If your method overrides one of its superclasss
    methods, you can still invoke the overridden
    method through the use of the keyword super.
  • super.overRiddenMethod()
  • Subclass Constructors
  • The super keyword can be used to invoke a
    superclasss constructor.
  • The syntax for calling a superclass constructor
    is
  • super() --or-- super(parameter list)

94
Object as a Superclass
  • The Object class, in the java.lang package, sits
    at the top of the class hierarchy tree.
  • Every class is a descendant, direct or indirect,
    of the Object class.
  • Every class you use or write inherits the
    instance methods of Object.
  • For example, the Objects toString() method
    returns a string that textually represents this
    object.
  • String myObjectString myObject.toString()

95
What Is an Interface?
  • Objects define their interaction with the outside
    world through the methods that they expose.
  • Methods form the objects interface with the
    outside world.
  • For example,
  • the buttons on the front of your television set
    are the interface between you and the electrical
    wiring on the other side of its plastic casing.
  • You press the power button to turn the
    television on and off.

96
Motivation for Having an Interface
  • One of the main reasons for having an interface
    is
  • CONVENIENCE
  • Suppose you have written a group of re-usable
    classes and you wanted to give other Software
    Engineers easier access to the methods your group
    of classes provide.
  • If there existed a mechanism through which a
    class (or a group of classes) could somehow
    advertise or show what methods it provides, then
    this would make using the class (or group of
    classes) easier, since the users would not be
    exposed to, and, therefore, not have to be
    concerned about the internal or un-required
    features of the class.

97
What Is an Interface? Motivation
  • Java provides such a mechanism, called an
    interface.
  • An interface is a formal specification of the
    methods that a class (or a group of classes)
    implements.
  • In Java, an interface is a group of related
    methods with empty bodies.
  • A class (or group of classes) provides the
    implementation of the methods specified in the
    interface.

98
Interface Bicycle Example
  • To specify (or advertise) the methods that the
    Bicycle hierarchy provides, consider creating an
    interface called Bicycle.
  • interface Bicycle
  • void changeCadence(int newValue)
  • void changeGear(int newValue)
  • void speedUp(int increment)
  • void applyBrakes(int decrement)
  • Note the name of your Bicycle class would have
    to change. Using the name Bicycle for the
    interface is more appropriate than using it for
    the class. You might change the name to
    ACMEBicycle, and have the subclasses called
    ACMEMoutainBike, etc.)

99
Interface Bicycle Example
  • To implement this interface, use the implements
    keyword in the class declaration.
  • class ACMEBicycle implements Bicycle
  • void changeCadence(int newValue)
  • //implementation of changing the cadence.
  • void changeGear(int newValue)
  • //implementation of changing the gear.
  • interface Bicycle
  • void changeCadence(int newValue)
  • void changeGear(int newValue)

Note the Empty body for each method in the
interface.
100
UML Representation of Interface
Dashed line connects the class with the interface.
Interface
This class hierarchy implements the interface
Bicycle.
ACMEBicycle
speedUp changeGear
Closed, non-filled, dashed line triangle points
to the interface
101
Interface Rules (Java Specific)
  • Each class is allowed to implement any number of
    interfaces.
  • Each method specified in an interface cannot have
    any implementation.
  • Each method in an interface must have an empty
    body.
  • Each method specified in an interface must be
    implemented by some class in the source code.
  • If a class claims to implement an interface, all
    methods defined by that interface must appear in
    the classs source code.
  • Otherwise the class will not successfully compile.

102
Abstract Classes Possible Shape2D Hierarchy
Italics indicates Abstract Item (class or method).
103
Abstract Classes and Methods(Motivation)
  • Suppose you are trying to design a Shape2D class
    that practices and promotes reuse.
  • public class Shape2D
  • public double getArea()
  • // do nothing since insufficient information //
    regarding how to calculate the area.
  • public class Circle extends EllipticalShape
  • //user of Shape2D forgets to further define
    getArea()
  • Compiler does not force user to further define
    getArea(). Thus, this would be prone to error.

104
Abstract Classes and Methods
  • A better way,
  • public abstract class Shape2D
  • public abstract double getArea()
  • //separate file
  • public class Circle extends EllipticalShape
  • //user of Shape2D must provide a concrete
    //implementation of getArea()
  • Compiler forces user to define (implement)
    getArea(). A concrete implementation of getArea()
    must be defined by a subclass.

105
Abstract Classes and Methods
  • A method should be declared to exist at the
    highest class in the hierarchy where it makes
    sense.
  • The method may need to be declared abstract
  • i.e., lacking implementation at that level.
  • An abstract method is declared without an
    implementation (without curly braces, and
    followed by a semicolon).
  • public abstract double getArea()

106
Abstract Classes and Methods
  • If a method is abstract, the class must also be
    declared abstract
  • public abstract class Shape2D
  • No instances can be created.
  • The opposite of an abstract class is a concrete
    class.
  • If a superclass has an abstract method then its
    subclasses at some level must have a concrete
    method.
  • Leaf classes must have or inherit concrete
    methods.
  • Leaf classes must be concrete.

107
Abstract Class Members
  • Abstract classes can contain instance fields and
    implemented (concrete) instance methods.
  • An abstract class may have static fields and
    static methods.
  • You can use these static members with a class
    reference.
  • for example, AbstractClass.staticMethod()
Write a Comment
User Comments (0)
About PowerShow.com