Class and Method Modifiers - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

Class and Method Modifiers

Description:

Class and Method Modifiers Roderick Rodriguez, Dianne Musciano, Sukumar Simhadri, George Blank Modifiers Modifiers are Java keywords that extend or place limits on ... – PowerPoint PPT presentation

Number of Views:201
Avg rating:3.0/5.0
Slides: 66
Provided by: GeorgeB156
Category:

less

Transcript and Presenter's Notes

Title: Class and Method Modifiers


1
Class and Method Modifiers
  • Roderick Rodriguez, Dianne Musciano, Sukumar
    Simhadri,
  • George Blank

2
Modifiers
  • Modifiers are Java keywords that extend or place
    limits on defined classes, fields, methods, and
    sub-classes.
  • Imagine that we are creating a game and want to
    simulate a pair of dice. We might define a die
    class, shown graphically on the next slide.

3
Class Example Die
  • A class has a name and can contain data
    declarations and/or method declarations

Die
Class Name
- faceValue integer roll() integer
Data declarations
Method declarations
4
Definitions for Die
  • class a specification of all the data, and
    behavior for a single die.
  • object a die class that has been instantiated
    in a running program
  • field a data attribute or variable like
    faceValue used by the class
  • method a specification of behavior like roll()
    used by the class

5
Object Class
  • Object
  • Abstracts away (data, algorithm) details
  • Encapsulates data
  • Instances exist at run time
  • Class
  • Blueprint for objects (of same type)
  • Exists at compile time

6
How die works
  • The values of the data define the state of an
    object created from the class
  • The functionality of the methods define the
    behaviors of the object
  • For our Die class, we might declare an integer
    that represents the current value showing on the
    face
  • One of the methods would allow us to roll the
    die by setting its face value to a random number
    between one and six

7
Super and Sub Classes
  • The extends clause specifies the super class
    of this class. The implements clause specifies
    the interfaces being implemented by this class.
    Member declarations can be declarations of
    fields, methods, and nested classes. The field,
    method, and nested class declarations can be
    intermixed. The order of declarations is
    immaterial to the compiler. Thus, they should be
    ordered in a way that is most logical and
    comprehensible.

8
Modifiers
  • Modifiers in Java can define accessibility and
    can be applied to both classes and class members
    (sub-classes, fields and methods).
  • Some of the modifier keywords are shared by both
    classes and methods.
  • When using access modifiers only one can be used
    at a time.

9
Scope, Visibility, Accessibility
  • Scope refers to the boundaries of programs and
    components of programs.
  • Visibility refers to portions of the scope that
    can be known to a component of a program.
  • Accessibility refers to portions of the scope
    that a component can interact with.

10
Scope
  • Scope
  • Part of program where a variable may be
    referenced
  • Determined by location of variable declaration
  • Boundary usually demarcated by
  • Example
  • public MyMethod1()
  • int myVar myVar accessible in
  • ... method between

11
Scope Example
Scope
  • package edu.umd.cs
  • public class MyClass1
  • public void MyMethod1()
  • ...
  • public void MyMethod2()
  • ...
  • public class MyClass2

Method
Class
Package
Method
Class
12
Accessibility/Visibility Modifiers
  • Modifiers can control visibility/accessibility.
  • These modifiers are used to implement the
    object-oriented principles of abstraction and
    encapsulation.
  • Visibility and Accessibility are normally used
    interchangeably, since visible components are
    normally accessible and accessible components are
    normally visible.

13
Other Modifiers
  • In addition to scope, modifiers can refer to
    related concepts, such as limiting access to a
    thread in a multithreaded environment
    (synchronized) or indicating that a method or
    field belongs to the whole class instead of a
    single instance (static).

14
Modifier Examples
  • public class MyApplet extends java.applet.Applet
  • private boolean killJabberwork
  • static final double weeks 9.5
  • protected static final int MEANINGOFLIFE 42
  • public static void main(String arguments

15
Class Modifiers
  • Class modifiers include the following
  • ltnonegt  - When no modifier is present, by default
    the class is accessible by all the classes within
    the same package.
  • public - A public class is accessible by any
    class.     
  • abstract - An abstract class contains abstract
    methods.
  • final - A final class may not be extended, that
    is, have subclasses.

16
Class Modifiers
  • Syntax for class modifiers
  • ClassModifier class ClassName
  • Example
  • public class Employee

17
Class Modifiers
  • Important points for class modifiers
  • A single Java file can only contain one class
    that is declared public.
  • An abstract class cannot be instantiated.
  • A static nested class does not have an implicit
    reference to the enclosing class.

18
Method Modifiers
  • Method Modifiers include the following
  • ltnonegt - When no modifier is present, by default
    the method is accessible by all the classes
    within the same package.
  • public - A public method is accessible by any
    class.
  • protected -A protected method is accessible by
    the class itself, all its subclasses.
  • private - A private method is accessible only by
    the class itself.

19
Method Modifiers
  • static - accesses only static fields. 
  • final - may not be overridden in subclasses.
  • abstract - defers implementation to its
    subclasses.
  • synchronized - atomic in a multithreaded
    environment
  • native - compiled to machine code by Assembler, C
    or C.

20
Method Modifiers
  • Syntax for method modifiers
  • MethodModifers ReturnType MethodName
    (ParameterList)
  • Example
  • private void GetEmployee(int ID)

21
Method Modifiers
  • Important points for method modifiers
  • Abstract methods must be contained in an abstract
    class.
  • Static methods cannot be overridden in a child
    class but they can be hidden.
  • Methods may not be overridden to be more private.
    For example, a protected method can not be
    overridden by a default one. A default method
    can be overridden by a protected or public method.

22
Field (variable) Only Modifiers
  • volatile may be modified by nonsynchronized
    methods in a multithread environment
  • transient not part of the persistent state of
    instantiated objects

23
Visibility Modifier
  • Properties
  • Controls access to class members
  • Applied to instance variables methods
  • Four types of access in Java
  • Public Most visible
  • Protected
  • Package
  • Default if no modifier specified
  • Private Least visible

24
Visibility Modifier Where Visible
  • public
  • Referenced anywhere (i.e., outside package)
  • protected
  • Referenced within package, or by subclasses
    outside package
  • None specified (package)
  • Referenced only within package
  • private
  • Referenced only within class definition
  • Applicable to class fields methods

25
Member Visibility Modifiers
  • Members of a class that are declared with public
    visibility can be referenced anywhere
  • Members of a class that are declared with private
    visibility can be referenced only within that
    class
  • Members declared without a visibility modifier
    have default visibility and can be referenced by
    any class in the same package

26
Field Visibility Modifiers
  • For instance variables
  • Should usually be private to enforce
    encapsulation
  • Sometimes may be protected for subclass access

27
Field Visibility Modifiers
  • Public variables violate the spirit of
    encapsulation because they allow the client to
    reach in and modify the objects internal
    values directly
  • Therefore, instance variables should not be
    declared with public visibility
  • It is acceptable to give a constant public
    visibility, which allows it to be used outside of
    the class
  • Public constants do not violate encapsulation
    because, although the client can access it, its
    value cannot be changed

28
Method Visibility Modifiers
  • For methods
  • Public methods provide services to clients
  • Private methods provide support other methods
  • Protected methods provide support for subclass

29
Method Visibility Modifiers
  • Methods that provide the object's services are
    declared with public visibility so that they can
    be invoked by clients
  • Public methods are also called service methods
  • A method created simply to assist a service
    method is called a support method
  • Since a support method is not intended to be
    called by a client, it should be declared with
    private - not with public visibility

30
Modifier - Private
  • Private methods and variables are particularly
    useful in two circumstances
  • When other classes have no reason to use that
    variable or method
  • When another class could wreak havoc by changing
    a variable in an inappropriate way

31
Visibility Modifiers - Summary
Enforce encapsulation
Violate encapsulation
Support other methods in the class
Provide services to clients
32
Static Methods
  • Methods declared with static modifier
  • Can be defined in any class
  • Not associated with an object
  • Is not invoked by sending it as a message to an
    object
  • The class method foo in the class C is invoked
    using the notation foo.C( )
  • It has no receiver and cannot refer to instance
    variables
  • It can refer to and manipulate class variables

33
Modifier Static
  • Static variable
  • Single copy for class
  • Shared among all objects of class
  • Static method
  • Can be invoked through class name
  • Does not need to be invoked through object
  • Can be used even if no objects of class exist
  • Can not reference instance variables

34
Modifier Final
  • Final variable
  • Value can not be changed
  • Must be initialized in every constructor
  • Attempts to modify final are caught at compile
    time
  • Final static variable
  • Used for constants
  • Example
  • final static int Increment 5

35
Modifier Final
  • Final method
  • Method can not be overloaded by subclass
  • Private methods are implicitly final
  • Final class
  • Class can not be a superclass (extended)
  • Methods in final class are implicitly final

36
Modifier Final
  • Final classes
  • Prevent inheritance / polymorphism
  • May be useful for
  • Security
  • Object oriented design
  • Example class String is final
  • Programs can depend on properties specified in
    Java library API
  • Prevents subclass from bypassing security
    restrictions

37
Modifier Abstract
  • Description
  • Represents generic concept
  • Can not be instantiated
  • Abstract class
  • Placeholder in class hierarchy
  • Can be partial description of class
  • Can contain non-abstract methods
  • Required if any method in class is abstract

38
All possible combinations of Features and
Modifiers
Modifier Class Variable Method Constructor
Free-Floating Block Public y y
y y
n Protected n y y
y n Default y y
y y
y Private n y y
y n Final y
y y n
n Abstract y n y
n n Static n
y y n
y
39
All possible combinations of Features and
Modifiers
Modifier Class Variable Method Constructor
Free-Floating Block Native n n
y n
n Transient n y n
n n Volatile n y
n n
n Synchro- n n y
n y nized
40
A variation of Murphys Law
  • One of the statements of Murphys law, as applied
    to programming, is
  • All variables are constant, and
  • All constants are variable
  • The final key word is concerned with
    immutability. This final section of the lecture
    is based on a Wikipedia discussion of
    immutability.

41
Introduction to Immutability
  • Immutable means not changeable
  • All Java variables are by default mutable. You
    can make them immutable by using the final
    keyword.
  • The wrapper classes, Byte, Character, Short,
    Integer, Long, Float and Double are all
    immutable.
  • Strings are immutable( StringBuffers are mutable
    ). The only way to change the value of the number
    inside the object wrapper is to create a new
    object and point to that instead.

42
Properties of Immutable Objects
  • Immutable objects have a number of properties
    that make working with them easier, including
    relaxed synchronization requirements and the
    freedom to share and cache object references
    without concern for data corruption.
  • An immutable object is one whose externally
    visible state cannot change after it is
    instantiated. The String, Integer, and BigDecimal
    classes in the Java class library are examples of
    immutable objects -- they represent a single
    value that cannot change over the lifetime of the
    object.

43
Creating an Immutable class
  • Writing immutable classes is easy. A class will
    be immutable if all of the following are true
  • All of its fields are final
  • The class is declared final
  • The this reference is not allowed to escape
    during construction

44
References to mutable objects in immutable
classes
  • Any fields that contain references to mutable
    objects, such as arrays, collections, or mutable
    classes like Date
  • Are private
  • Are never returned or otherwise exposed to
    callers
  • Are the only reference to the objects that they
    reference
  • Do not change the state of the referenced objects
    after construction

45
String example
  • String s "ABC"
  • s.toLower()
  • // The method toLower() will not change the data
    "ABC" that s contains. Instead, a new String
    object is instantiated and given the data "abc"
    during its construction. A reference to this
    String object is returned by the toLower()
    method. To make the String s contain the data
    "abc", a different approach is needed.
  • s s.toLower()
  • // Now the String s references a new String
    object that contains "abc". The String class's
    methods never affect the data that a String
    object contains.

46
Are constants still variable?
  • Immutability does not guarantee that the object
    as stored in the computer's memory is
    unwriteable. Rather, immutability is a compile
    time construct that indicates what a programmer
    should do, not necessarily what he can do (for
    instance, by circumventing the type system or
    violating constant corrections in C or C).
    Java has more protection against violating
    constraints than C or C, but circumvention may
    still be possible.

47
Copy on Write
  • A technique which blends the advantages of
    mutable and immutable objects, and is supported
    directly in almost all modern hardware, is
    copy-on-write (COW). Using this technique, when a
    user asks the system to copy an object, it will
    instead merely create a new reference which still
    points to the same object. As soon as a user
    modifies the object through a particular
    reference, the system makes a real copy and sets
    the reference to refer to the new copy. The other
    users are unaffected, because they still refer to
    the original object.

48
Benefit of Copy on Write
  • Under COW, all users appear to have a mutable
    version of their objects, although if users do
    not modify their objects, the space-saving and
    speed advantages of immutable objects are
    preserved. Copy-on-write is popular in virtual
    memory systems because it saves memory space in
    the core while still correctly handling anything
    an application program might do.

49
Immutable Colors
  • An example of immutability in the Java class
    library is java.awt.Color. While colors are
    generally represented as an ordered set of
    numeric values in some color representation (such
    as RGB, HSB, or CMYK), it makes more sense to
    think of a color as a distinguished value in a
    color space, rather than an ordered set of
    individually addressable values, and therefore it
    makes sense to implement Color as an immutable
    class.

50
Immutable Events
  • Events are another example of good candidates for
    implementation with immutable classes. Events are
    short-lived, and are often consumed in a
    different thread than they were created in, so
    making them immutable has more advantages than
    disadvantages.

51
Where to use it ?
  • Should containers for multiple primitive values,
    such as points, vectors, matrices, or RGB colors,
    be mutable or immutable objects? It depends on
    how are they going to be used. Are they used
    primarily to represent multi-dimensional values
    (like the color of a pixel), or simply as
    containers for a collection of related properties
    of some other object (like the height and width
    of a window)? How often are these properties
    going to be changed? If they are changed, do the
    individual component values have meaning within
    the application on their own?

52
Benefits of immutability
  • Immutable classes, when used properly, can
    greatly simplify programming. They can only be in
    one state, so as long as they are properly
    constructed, they can never get into an
    inconsistent state.
  • You can freely share and cache references to
    immutable objects without having to copy or clone
    them.
  • Immutable classes generally make the best map
    keys. And they are inherently thread-safe, so you
    don't have to synchronize access to them across
    threads.

53
Freedom to cache
  • Because immutable objects do not change their
    value, you can freely cache references to them
    and be confident that the reference will refer to
    the same value later. Similarly, because their
    properties cannot change, you can cache their
    fields and the results of their methods.
  • If an object is mutable, you have to exercise
    some care when storing a reference to it.
    Consider the code in Listing 1, which queues two
    tasks for execution by a scheduler. The intent is
    that the first task would start now and the
    second task would start in one day.

54
Potential problem with a mutable Date object
  • Date d new Date()
  • Scheduler.scheduleTask(task1, d)
  • d.setTime(d.getTime() ONE_DAY)
  • scheduler.scheduleTask(task2, d)
  • Because Date is mutable, the scheduleTask method
    must defensively copy the date parameter
    (clone()) into its internal data structure.
    Otherwise, task1 and task2 might both execute
    tomorrow. Worse, the internal data structure
    could become corrupt.

55
Debugging the mutable Date example (previous
slide)
  • It is very easy to forget to defensively copy the
    date parameter when writing a method like
    scheduleTask(). If you do forget, you've created
    a subtle bug that's not going to show up for a
    while, and one that will take a long time to
    track down when it does. An immutable Date class
    would have made this sort of bug impossible.

56
Benefits of Immutability
  • The freedom to share references to immutable
    objects across threads without synchronization
    can greatly simplify the process of writing
    concurrent programs and reduces the number of
    potential concurrency errors a program could
    have.

57
Safety with ill-behaved code
  • Methods that take objects as arguments should not
    mutate the state of those objects. When we pass
    an object to an ordinary method, we do not expect
    that the object will come back changed. If we
    pass a java.awt.Point to a method such as
    Component.setLocation(), setLocation can modify
    the location of the Point we pass in or store a
    reference to that point and change it later in
    another method. Now, the state of the Point has
    changed without our knowledge, with potentially
    hazardous results.

58
Immutable Keys
  • Immutable objects make the best HashMap or
    HashSet keys. Some mutable objects will change
    their hashCode() value depending on their state.
    If you use a mutable object as a HashSet key, and
    then the object changes its state, the HashSet
    implementation will become confused -- the object
    will still be present if you enumerate the set,
    but it may not appear to be present if you query
    the set with contains().

59
Shopping Cart example
  • class Cart
  • private final List items
  • public Cart(List items)
  • this.items items
  • public List getItems() return items
  • public int total()
  • / return sum of the prices /

60
Shopping Cart explanation
  • An instance of this class is not immutable one
    can add or remove items either by obtaining the
    field items by calling getItems() or by retaining
    a reference to the List object passed when an
    object of this class is created. The following
    code partially solves this problem. In the
    ImmutableCart class, the list is immutable you
    cannot add or remove items.

61
Shopping Cart solution
  • The decorator pattern used as a wrapper around
    each of the list's items makes them immutable.
  • class ImmutableCart
  • private final List items
  • public ImmutableCart(List items)
  • this.items
  • Arrays.asList(items.toArray())
  • public List getItems() return
    Collections.unmodifiableList(items)
  • public int total() / return sum of the prices
    /

62
Summary of Immutability
  • You can share immutable objects between threads
    without danger of changes confusing the other
    thread.
  • Once you check the value, you know it has to stay
    safe. No one can pass you a value, then behind
    your back swap it to an unsafe one. This is
    particularly important in high security
    situations where allowing an invalid value to
    sneak in could compromise system integrity, e.g.
    a filename.

63
Summary
  • You can share duplicate objects by pointing them
    to a single instance.
  • You can create substrings without copying.
    Immutability is the secret behind Java's very
    fast substring implementation.
  • Immutable objects are much better suited to be
    Hashtable keys. If you change the value of an
    object that is used as a hash table key without
    removing it and re-adding it you lose the
    mapping.

64
Returning an Immutable Result
  • How would you return some data from a method
    without changing the original. Here are four
    ways
  • Wrap the reference in an immutable wrapper class
    and return that.
  • Give the caller a private copy of the data.
  • Request that the user not to modify the data.
  • Return an immutable interface to the original
    data. You can then change fields in the object,
    but the caller cannot unless he cheats by
    casting. Expose only the methods you want the
    user to have. Doing this with classes is harder
    since a subclass must expose everything its
    superclass does.

65
Bibliography
  • Jia, Xiaoping, Object Oriented Software
    Development, using Java. Addison Wesley, 2003.
  • Declarations and access control. Certkey for
    Java2. 26 April 2006 http//www.jchq.net/certkey/
    0102certkey.htm
  • Java 2 Basics Modifiers. GARBA.ORG. 26 April
    2006 http//www.garba.org/documents/java2/modifier
    s.html
  • http//www.answers.com/topic/immutable-object
Write a Comment
User Comments (0)
About PowerShow.com