1 / 65

Class and Method Modifiers

Class and Method Modifiers. Roderick Rodriguez, Dianne Musciano, Sukumar Simhadri, George Blank. Modifiers. Modifiers are Java keywords that extend or place limits on defined classes, fields, methods, and sub-classes.

betty_james
Download Presentation

Class and Method Modifiers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 extendsclause specifies the super class of this class. The implementsclause 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. public class MyApplet extends java.applet.Applet{…} private boolean killJabberwork; static final double weeks = 9.5; protectedstatic final int MEANINGOFLIFE = 42 public static void main(String arguments[]{…} Modifier Examples

  15. Class Modifiers • Class modifiers include the following: • <none>  - 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: • <none> - 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 bysubclasses 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 object’s 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. public private Variables Methods Visibility Modifiers - Summary Violate encapsulation Enforce 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 Murphy’s Law • One of the statements of Murphy’s 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.

More Related