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

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

  • View
    217

  • Download
    1

Embed Size (px)

Citation preview

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

Class Modifiers

• So far we have seen many examples of such modifiers

• E.g.

• Public

• Abstract etc

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

Terminology

• Access Modifier– determines access rights for the class and its

members– defines where the class and its members can

be used

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

Class Modifiers

• A class declaration may include class modifiers. • ClassModifiers: ClassModifier ClassModifiers

ClassModifier ClassModifier: one of • public • protected • private • abstract • static • final • strictfp

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

Field Modifiers

• FieldModifiers: • FieldModifier FieldModifiers • FieldModifier FieldModifier: one of • public • protected • private • static • final • transient • volatile

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

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

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

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

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

Access Modifiers

Access Modifier Class or member can be referenced by…

public methods of the same class, and methods of other classes

private methods of the same class only

protected methods 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

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

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

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

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!

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

Private

• Private if its only visible from inside the class definition

• This is compromised somewhat by public access methods

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

Example

• public class Secret {

• private String theSecret;

• private String getSecret (){

• ...

• }

• }

• Both theSecret and getSecret variables are only accessible inside the class

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

Consider

public class NotSoSecret extends Secret {

...

public void getSecret(){

super.getSecret();

...

}

}• You can’t access getSecret by inheritance

because its private

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

• 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

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

Class Modifiers

• A class declaration may include class modifiers. • ClassModifiers: ClassModifier ClassModifiers

ClassModifier ClassModifier: one of • public • protected • private • abstract • static • final • strictfp

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

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

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

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

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

Examples of Instance Variable Definitions

private String name = "";

private final int PERFECT_SCORE = 100,

PASSING_SCORE = 60;

private int startX, startY,

width, height;

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

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.

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

The Auto Class

public class Auto

{

private String model;

private int milesDriven;

private double gallonsOfGas;

}

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

Field Modifiers

• FieldModifiers: • FieldModifier FieldModifiers • FieldModifier FieldModifier: one of • public • protected • private • static • final • transient • volatile

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

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

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

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;

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

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.

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

Rules for static and Non-static Methods

• See Examples 7.12 and 7.13

static Method

Non-static Method

Access instance variables? no yes

Access static class variables? yes yes

Call static class methods? yes yes

Call non-static instance methods?

no yes

Use the object reference this? no yes

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

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

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

Example

private final int PERFECT_SCORE = 100,

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

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

• ...

• }

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

Then the following would not be allowed:

• class Programmer extends Person {

• ...

• // the body of the class

• ...

• }

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

Transient and volatile

• We will go back to these

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

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.

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

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.

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

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

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

Value-Returning Methods

• Use a return statement to return the value

• Syntax: return expression;

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

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).

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

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.

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

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

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

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)

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

Accessor Methods

• Example: the accessor method for model.

public String getModel( )

{

return model; }

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

Mutator Methods

• Allow client to change the values of instance variables

public void setInstanceVariable(

dataType newValue )

{

// validate newValue,

// then assign to instance variable

}

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

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." );

}

}

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

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;

}

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

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

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

Using this in a Mutator Methodpublic 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.

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

The toString Method

• Returns a String representing the data of an object

• Client can call toString explicitly by coding the method call.

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

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 );

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

The toString API

Return value

Method name and argument list

String toString( )

returns a String representing the data of an object

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

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 );

}

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

The equals Method

• Determines if the data in another object is equal to the data in this objectReturn value Method name and argument list

boolean equals( Object obj )

returns true if the data in the Object obj is the same as in this object; false otherwise.

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

Example

• Example client code using Auto references auto1 and auto2:

if ( auto1.equals( auto2 ) )

System.out.println( "auto1 equals auto2" );

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

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;

}

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

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

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

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

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

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;

}

}

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

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

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

• 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

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

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