Presentation is loading. Please wait.

Presentation is loading. Please wait.

Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc.

Similar presentations


Presentation on theme: "Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc."— Presentation transcript:

1 Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc

2 Terminology Access Modifier –determines access rights for the class and its members –defines where the class and its members can be used

3 Class Modifiers A class declaration may include class modifiers. ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final strictfp

4 Field Modifiers FieldModifiers: FieldModifier FieldModifiers FieldModifier FieldModifier: one of public protected private static final transient volatile

5 Why use these It is important in many applications to hide data from the programmer E.g., a password program must be able to read in a password and compare it to the current one or allow it to be changed But the password should never be accessed directly! public class Password { public String my_password; : } Password ProtectMe; : ProtectMe.my_password = “backdoor”; // this is bad

6 Public etc public means that any class can access the data/methods private means that only the class can access the data/methods protected means that only the class and its subclasses can access the data/methods

7 Access Modifiers Access ModifierClass or member can be referenced by… publicmethods of the same class, and methods of other classes privatemethods of the same class only protectedmethods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package access) methods in the same package only

8 public vs. private Classes are usually declared to be public Instance variables are usually declared to be private Methods that will be called by the client of the class are usually declared to be public Methods that will be called only by other methods of the class are usually declared to be private

9 public Public access Most liberal kind of access Class or field is accessible everywhere When a method or variable is labelled with the keyword public it means that any other class or object can use that public method or variable When a class is labelled with the keyword public, it means the class can be used by any other class The keyword private is used to restrict access and prevent inheritance!

10 Private Private if its only visible from inside the class definition This is compromised somewhat by public access methods

11 Example public class Secret { private String theSecret; private String getSecret (){... } Both theSecret and getSecret variables are only accessible inside the class

12 Consider public class NotSoSecret extends Secret {... public void getSecret(){ super.getSecret();... } You can’t access getSecret by inheritance because its private

13 Secret mySecret; NotSoSecret myDiary;... mySecret.getSecret(); myDiary.getSecret(); Cannot invoke the getSecret method on mySecret since it’s private. Can invoke getSecret on myDiary because it’s public in class NotSoSecret

14 Class Modifiers A class declaration may include class modifiers. ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final strictfp

15 strictfp Classes The effect of the strictfp modifier is to make all float or double expressions within the class declaration be explicitly FP-strict This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp. Don’t worry about this for now

16 Defining Instance Variables Syntax: accessModifier dataType identifierList; dataType can be primitive date type or a class type identifierList can contain: –one or more variable names of the same data type –multiple variable names separated by commas –initial values Optionally, instance variables can be declared as final

17 Examples of Instance Variable Definitions private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

18 Tips Define instance variables for the data that all objects will have in common. Define instance variables as private so that only the methods of the class will be able to set or change their values. Begin the identifier name with a lowercase letter and capitalize internal words.

19 The Auto Class public class Auto { private String model; private int milesDriven; private double gallonsOfGas; }

20 Field Modifiers FieldModifiers: FieldModifier FieldModifiers FieldModifier FieldModifier: one of public protected private static final transient volatile

21 static If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized

22 static Variables Also called class variables One copy of a static variable is created per class static variables are not associated with an object static constants are often declared as public To define a static variable, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName; Example: public static int countAutos = 0;

23 static Methods Also called class methods Often defined to access and change static variables static methods cannot access instance variables: – static methods are associated with the class, not with any object. –static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access.

24 Rules for static and Non-static Methods See Examples 7.12 and 7.13 static Method Non-static Method Access instance variables?noyes Access static class variables?yes Call static class methods?yes Call non-static instance methods? noyes Use the object reference this?noyes

25 final Fields A field can be declared final Both class and instance variables (static and non-static fields) may be declared final. Effectively final declares the variable to be constant

26 Example private final int PERFECT_SCORE = 100,

27 To stop a class being inherited from (sub-classes) we can declare it as a final class e.g. If Person was declared as final final class Person {... // the body of the class... }

28 Then the following would not be allowed: class Programmer extends Person {... // the body of the class... }

29 Transient and volatile We will go back to these

30 Method Return Types The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void. Methods with a return type of void do not return a value to the caller.

31 Method Body The code that performs the method's function is written between the beginning and ending curly braces. Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

32 main is a Method public static void main( String [] args ) { // application code } Let's look at main's API in detail: public main can be called from outside the class. (The JVM calls main.) static main can be called by the JVM without instantiating an object. void main does not return a value String [] args main's parameter is a String array

33 Value-Returning Methods Use a return statement to return the value Syntax: return expression;

34 Class Scope Instance variables have class scope –Any constructor or method of a class can directly refer to instance variables. Methods also have class scope –Any method or constructor of a class can call any other method of a class (without using an object reference).

35 Local Scope A method's parameters have local scope, meaning that: –a method can directly access its parameters. –a method's parameters cannot be accessed by other methods. A method can define local variables which also have local scope, meaning that: –a method can access its local variables. –a method's local variables cannot be accessed by other methods.

36 Summary of Scope A method in a class can access: –the instance variables of its class –any parameters sent to the method –any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first –any methods in the class

37 Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable)

38 Accessor Methods Example: the accessor method for model. public String getModel( ) { return model; }

39 Mutator Methods Allow client to change the values of instance variables public void setInstanceVariable( dataType newValue ) { // validate newValue, // then assign to instance variable }

40 Mutator Methods Example: the mutator method for milesDriven public void setMilesDriven( int newMilesDriven ) { if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven; else { System.err.println( "Miles driven " + "cannot be negative." ); System.err.println( "Value not changed." ); }

41 Data Manipulation Methods Perform the "business" of the class. Example: a method to calculate miles per gallon: public double calculateMilesPerGallon( ) { if ( gallonsOfGas != 0.0 ) return milesDriven / gallonsOfGas; else return 0.0; }

42 The Object Reference this How does a method know which object's data to use? this is an implicit parameter sent to methods and is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied Thus: variableName model is understood to be is understood to be this.variableName this.model

43 Using this in a Mutator Method public void setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Example: public void setModel( String model ) { this.model = model; } this.model refers to the instance variable. model refers to the parameter.

44 The toString Method Returns a String representing the data of an object Client can call toString explicitly by coding the method call.

45 Example Client can call toString implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // explicit toString call System.out.println( compact.toString( ) ); // implicit toString call System.out.println( compact );

46 The toString API Return value Method name and argument list StringtoString( ) returns a String representing the data of an object

47 Auto Class toString Method public String toString( ) { DecimalFormat gallonsFormat = new DecimalFormat( "#0.0" ); return "Model: " + model + "; miles driven: " + milesDriven + "; gallons of gas: " + gallonsFormat.format( gallonsOfGas ); }

48 The equals Method Determines if the data in another object is equal to the data in this object Return valueMethod name and argument list booleanequals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise.

49 Example Example client code using Auto references auto1 and auto2: if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" );

50 Auto Class equals Method public boolean equals( Auto autoA ) { if ( model.equals( autoA.model ) && milesDriven == autoA.milesDriven && Math.abs( gallonsOfGas - autoA.gallonsOfGas ) < 0.0001 ) return true; else return false; }

51 Consider A bank account always has methods for depositing and querying the balance To maintain the privacy of a client’s balance and still allow methods in subclasses to change the balance we need to introduce a new access modifier called protected

52 protected If you create a protected data field or method it can be used within its own class or any subclass extended from it but not from the outside world

53

54 Example A standard bank account implements methods for depositing and querying the current balance: public class StandardAccount extends Account { protected double balance; Account (){ balance = 0.0; } public void lodgement (double amt){ balance = balance + amt; } public double getBalance (){ return balance; }

55 Exercises 1. True or false? Any of the access modifiers, public, protected, or private, can be applied to a top-level class. 2. Which, if any, of the following declarations are legal? A. public MyClass {//...} B. public protected int myVar; C. friendly Button myButton; D. Label myLabel

56 3. True or false? Access modifiers control which classes may use a feature. A class' features are: The class itself. Its class variables. Its methods and constructors

57 4. True or false? Top-level classes that are declared private may be accessed only by other classes in the same package.


Download ppt "Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc."

Similar presentations


Ads by Google