Sin título de diapositiva - Departamento de Ingeniería de Sistemas e ...

clumpsmackoverΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 4 μήνες)

71 εμφανίσεις

Universidad Nacional de Colombia

Facultad de Ingeniería

Departamento de Ingeniería de Sistemas

ertificación en

AVA

3. MODIFIERS



Objectives



Modifiers



Other Modifiers

Objectives


Declare classes, inner classes, methods, instance variables,

static variables and automatic (method local) variables,

making appropriate use of all permitted modifiers (such

as public, final, static, abstract, and so forth).

State the significance of each of these modifiers both

singly and in combination, and state the effect of package

relationships on declared items qualified by these modifiers.


Modifiers


Specify that a particular feature is static,
final or transient


feature:

a class, a method, or a variable


A group of modifiers (access modifiers)
dictate which classes are allowed to use a
feature


Other modifiers can be used in combination
to describe the attributes of a feature


Keywords that give the compiler information about
the nature of code, data or classes.

class Parser{ ... }

public class EightDimensionalComplex{ ... }

private int i;

Graphics offScreenGC;

protected double getChiSquared() { ... }

private class Horse { ... }

Some Legal declarations

public protected int x; // at most 1




//access modifier allowed

friendly Button getBtn() {...} // friendly is not a


// modifier

Illegal declarations



The
most

generous access modifier



A public class, variable, or method may be used in
any java program without restriction



An applet is declared as a public class so that it
may be instantiated by browsers



An application declares its
main()

method to be
public so that main() may be invoked from any
Java runtime environment

public



The
least

generous access modifier



Top
-
level classes may not be declared
private



A private variable may only be used by an
instance of the class the class that declares
the variable or method

private

1.
class Complex{

2.

private double real, imaginary;


3.

public Complex( double r, double i) {

4.


real=r; imaginary=i; }


5.

public Complex add(Complex c) {

6.


return new Complex(real + c.real,

7.

imaginary+ c.imaginary);

8.

}

9.
}

10.


11.
class Client {

12.

void useThem() {

13.


Complex c1 =new Complex(1, 2);

14.



Complex c2 =new Complex(3, 4);

15.


Complex c3 =c1.add(c2);

16.



double d=c3.real; // Illegal!

17.

}

18.
}



Private data is hidden from every object
other than the one that owns the data



If class Complex has a subclass called
SubComplex, then every instance of
SubComplex will inherit its own real and
imaginary variables; an instance of a
subclass is denied access

1.
class Complex{

2.

private double real, imaginary;


3.

public Complex add(Complex c) {

4.


return new Complex(real + c.real,

1.
imaginary + c.imaginary);

5.

}

6.
}


7.
class SubComplex extends Complex {

8.

SubComplex(double r, double i) {

9.


real = r;

// compiler error

10.

}

11.
}



Is the name of the default access of
classes, variables and methods


A class’ data and methods may be friendly
as the class itself


A class’ friendly features are accessible to
any class in the same


Friendly is not a java keyword



Java considers that all classes in the
directory actually make up a package

friendly

package

class

Class

Class

Class

Class

Class

Class

Class

Class

protected

Only variables, methods, and inner
classes may be declared
protected



protected features are even more accessible than
friendly features


A protected feature is available to all classes in the
same package, just like a friendly feature



A protected feature is available to all the subclasses
of the class that owns the protected feature


This access is provided even to subclasses that reside
in a different package from the class that owns the
protected feature

package sportinggoods;

class Ski {


void applywax() { ... }

}

package sportinggoods;

class DownhillSki extends Ski {


void tuneup() {



applywax();



// other tuneup functionality here


}

}

package adifferentpackage; // class Ski now in a





// different package

class Ski {


protected void applymax() { ... }

}

package sportinggoods;

class DownhillSki extends Ski {


void tuneup() {



applywax();



// other tuneup functionality here


}

}

Methods may not be overridden to be more private

Subclasses and Method privacy


A method with some particular access type may be
overriden by a method with a different access type,
provided there is a path from the original type to the
new type.

public

protected

friendly

private

Illegal access types for subclasses

private

protected

friendly

public


Java does not care about order of
appearance of modifiers:

public final


same as


final public

protected static



same as


static protected


Other Modifiers


Not every modifier can be applied to every kind of
feature.

Error:


Can’t subclass final classes”


class SubMath extends java.lang.Math


Applies to classes, methods, and variables


Final features may not be changed


A final class may not be subclassed


A final variable may not be modified once it has
been assigned a value


If a final variable is a reference to an object, it is
the reference that must stay the same, not the
object

final

1.

class Walrus {

2.

int weight;

3.

Walrus(int w) { weight = w; }

4.

}

5.


6.

class Tester {

7.

final Walrus w1=new Walrus(1500);

8.

void test() {

9.


w1=new walrus(1400); // Illegal

10.


w1.weight=1800;


// Legal

11.

}

12.

}



You
may not

change a final object reference


You
may

change data owned by an object that is
referred to by a final object reference variable

1.

class Mammal {

2.

final void getAround() { }

3.
}


4.
class Dolphin extends Mammal {

5.

void getAround() { }

6.
}


A final method may not be overriden

Compiler error:

“Final methods can’t be overriden”


Can be applied to classes and methods


A class that is abstract may not be instantiated


Abstract classes defer implementation to
subclasses


If a class contains one or more abstract
methods the compiler insists that the class must
be declared abstract

abstract

abstract void travel()

class Animal

void travel()

class Bird

void travel()

class Fish

void travel()

class Snake

The compiler insists that the class must be
declared abstract if any of the following is true


The class has one or more abstract methods


The class inherits one or more abstract
methods for which it does not provide
implementations


The class declares that it implements an
interface but does not provide implementation
for every method of that interface

In a way, abstract is the opposite of final:

A final class

MAY NOT

be subclassed

An abstract class

MUST

be subclassed

class Ecstatic {


static int x=0;



Ecstatic() { x++; }

}


Applies to variables, methods, and even a
strange kind of code that is not part of a
method


You can think of a static features as
belonging to a class, rather than being
associated with an individual instance of
the class

static

Bad form

Ecstatic e1 = new Ecstatic();

Ecstatic e2 = new Ecstatic();

e1.x = 100;

e2.x = 200;

reallyImportantVariable=e1.x;

1.

Via a reference to any instance of the
class:

Two ways to reference a static variable

Ecstatic e1 = new Ecstatic();

Ecstatic e2 = new Ecstatic();

Ecstatic.x = 100; // why did I do this?

Ecstatic.x = 200;

reallyImportantVariable=Ecstatic.x;

2.
Via the class name:

class SomeClass {


static int i=48;


int j=1;



public static void main(String args[]) {



i += 100;



j *= 5; // compiler error


}

}

Static methods are not allowed to use the non
-
static
features of their class.

Static methods are not concerned with individual
instances of a class.

They may be invoked before even a single instance
of the class is constructed.

class Xyz {


int w;


void bumpW() {



w++;


}

}

Non
-
static methods have an implicit variable
named this, which is a reference to the
object executing the method

Abbreviation for




this.w++;

1.
import java.awt.*;


2.
public class MyFrame extends Frame {

3.

Myframe() {

4.


setSize(300, 300);

5.

}

6.


7.

public static void main( String
[]

args ) {

8.


MyFrame theFrame=new Myframe();

9.


theFrame.setVisible(true);

10.

}

11.
}

If a static method needs to access a non
-
static variable or call a
non
-
static method, it must specify which instance of its
class owns teh variable or executes the method have an
implicit variable named this, which is a reference to the
object executing the method

class Cattle {


static void foo() { }

}


class Sheep extends Cattle {


void foo() { }

}

A static method may not be overrriden to
be non
-
static (and vice
-
versa)

Error:

“Static methods can’t be overrriden”


A static method may only access the static data
of its class; it may not access non
-
static data


A static method may only call the static methods
of its class; it may not call non
-
static methods


A static method has no this reference


A static method may not be overriden to be non
-
static

Summary (static)



It is legal for a class to contain static code that
does not exist within a method body



A class may have a block of initializer code that
is simply surrounded by curly braces and labeled
static

Static initializers

public class StaticDemo {


static int i=5;



static {



System.out.println(“Static code: i= “+ i++ );


}


public static void main( String [] args ) {



System.out.println(“main: i= “+ i++ );


}

}



the code inside the curlies is executed exactly
once at the time the class is loaded


At class
-
load time, all static initialization and all
free
-
floating static code are executed in order of
appearance within the class definition

Static initializer code

public class StaticDemo {


static int i=5;



static {



System.out.println(“Static code: i= “+ i++ );


}


public static void main( String[] args ) {



System.out.println(“main: i= “+ i++ );


}

}



Can refer only to methods



Indicates that the body of a method is to be
found elsewhere



In the case of abstact methods, the body is in a
subclass


With native methods, the body lies entirely
outside the Java Virtual Machine (JVM), in a
library


Native code is written in a non
-
java language,
and compiled for a single target machine type


When a native method is invoked, the libarry
that contains the native code ought ot be loaded
and available to the JVM

native

1.
class NativeExample {

2.

native void doSomethingLocal(int i);

3.

static {

4.


System.loadLibrary(“MyNativeLib”);

5.

}

6.
}

1.
nativeExample natex;

2.
natex=new NativeExample();

3.
natex.doSomethingLocal(5);

1.
nativeExample natex;

2.
natex=new NativeExample();

3.
natex.doSomethingLocal(5);



Callers of native methods do not have to
know that the method is native


The call is made the same way as if it
were non
-
native


Can be applied only to variables


A transient variable is not stored as part of its
object
´
s persistent state

transient

Many objects (specifically those that implement either the
Serializable

or
Externalizable

interfaces) can have their
state serialized and written to some destination outside
the JVM


This is done by passing the object to the
WriteObject()

method of the
ObjectOutputStream

class


If the stream is chained to a
FileOutputStream
, then the
object’s state is written to a file

If the stream is chained to a socket’s
OutputStream
, then the
object’s state is written to the network


In both cases the object can be reconstituted by reading it
from an

ObjectInputStream

1.
class WealthyCustomer extends Customer
implements Serializable {

2.

private float $wealth;

3.

private String accessCode;

4.

}

Once an object is written to a destination outside
JVM, none of Java’s elaborate security
mechanism is in effect


If an instance of this class were to be written to a
file or to the Internet, somebody could snoop the
access code

1.
class WealthyCustomer extends Customer
implements Serializable {

2.

private float $wealth;

3.

private transient String accessCode;

4.

}

Now the value of
accessCode

will not be written
out during serialization


Control access to critical code in
multithreaded programs


To be seen in chapter 7

synchronized



Only variables may be volatile



Such variables might be modified
asynchronously, so the compiler takes special
precautions (multi
-
processor environments)

volatile