Sie sind auf Seite 1von 12

UNIT-I

OBJECT:
Objects are key to understanding object-oriented technology. Look around right now and you'll
find many examples of real-world objects: your dog, your desk, your teleision set, your bicycle.
!eal-world objects share two characteristics: "hey all hae state and behavior. #ogs hae state
$name, color, breed, hungry% and behaior $barking, fetching, wagging tail%. &icycles also hae
state $current gear, current pedal cadence, current speed% and behaior $changing gear, changing
pedal cadence, applying brakes%. 'dentifying the state and behaior for real-world objects is a
great way to begin thinking in terms of object-oriented programming.
"ake a minute right now to obsere the real-world objects that are in your immediate area. (or
each object that you see, ask yourself two )uestions: *+hat possible states can this object be in,*
and *+hat possible behaior can this object perform,*. -ake sure to write down your
obserations. .s you do, you'll notice that real-world objects ary in complexity/ your desktop
lamp may hae only two possible states $on and off% and two possible behaiors $turn on, turn
off%, but your desktop radio might hae additional states $on, off, current olume, current station%
and behaior $turn on, turn off, increase olume, decrease olume, seek, scan, and tune%. 0ou
may also notice that some objects, in turn, will also contain other objects. "hese real-world
obserations all translate into the world of object-oriented programming.
. software object.
1oftware objects are conceptually similar to real-world objects: they too consist of state and
related behaior. .n object stores its state in fields $ariables in some programming languages%
and exposes its behaior through methods $functions in some programming languages%. -ethods
operate on an object's internal state and sere as the primary mechanism for object-to-object
communication. 2iding internal state and re)uiring all interaction to be performed through an
object's methods is known as data encapsulation 3 a fundamental principle of object-oriented
programming.
4onsider a bicycle, for example:
. bicycle modeled as a software object.
&y attributing state $current speed, current pedal cadence, and current gear% and proiding
methods for changing that state, the object remains in control of how the outside world is
allowed to use it. (or example, if the bicycle only has 5 gears, a method to change gears could
reject any alue that is less than 6 or greater than 5.
&undling code into indiidual software objects proides a number of benefits, including:
-odularity: "he source code for an object can be written and maintained independently of the
source code for other objects. Once created, an object can be easily passed around inside the
system.
'nformation-hiding: &y interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
4ode re-use: 'f an object already exists $perhaps written by another software deeloper%, you can
use that object in your program. "his allows specialists to implement7test7debug complex, task-
specific objects, which you can then trust to run in your own code.
8luggability and debugging ease: 'f a particular object turns out to be problematic, you can
simply remoe it from your application and plug in a different object as its replacement. "his is
analogous to fixing mechanical problems in the real world. 'f a bolt breaks, you replace it, not
the entire machine.
CLASS:
'n the real world, you'll often find many indiidual objects all of the same kind. "here may be
thousands of other bicycles in existence, all of the same make and model. 9ach bicycle was built
from the same set of blueprints and therefore contains the same components. 'n object-oriented
terms, we say that your bicycle is an instance of the class of objects known as bicycles. . class is
the blueprint from which indiidual objects are created.
"he following &icycle class is one possible implementation of a bicycle:
class &icycle :
int cadence ; </
int speed ; </
int gear ; 6/
oid change4adence$int new=alue% :
cadence ; new=alue/
>
oid change?ear$int new=alue% :
gear ; new=alue/
>
oid speed@p$int increment% :
speed ; speed A increment/
>
oid apply&rakes$int decrement% :
speed ; speed - decrement/
>
oid print1tates$% :
1ystem.out.println$*cadence:*AcadenceA* speed:*AspeedA* gear:*Agear%/
>>
"he syntax of the Baa programming language will look new to you, but the design of this class
is based on the preious discussion of bicycle objects. "he fields cadence, speed, and gear
represent the object's state, and the methods $change4adence, change?ear, speed@p etc.% define
its interaction with the outside world.
0ou may hae noticed that the &icycle class does not contain a main method. "hat's because it's
not a complete application/ it's just the blueprint for bicycles that might be used in an application.
"he responsibility of creating and using new &icycle objects belongs to some other class in your
application.
2ere's a &icycle#emo class that creates two separate &icycle objects and inokes their methods:
class &icycle#emo :
public static oid main$1tringCD args% :
77 4reate two different &icycle objects
&icycle bike6 ; new &icycle$%/
&icycle bikeE ; new &icycle$%/
77 'noke methods on those objects
bike6.change4adence$F<%/
bike6.speed@p$6<%/
bike6.change?ear$E%/
bike6.print1tates$%/
bikeE.change4adence$F<%/
bikeE.speed@p$6<%/
bikeE.change?ear$E%/
bikeE.change4adence$G<%/
bikeE.speed@p$6<%/
bikeE.change?ear$H%/
bikeE.print1tates$%/
>>
Method
. method is a group of instructions that is gien a name and can be called up at any point in a
program simply by )uoting that name. (or instance, we met an instruction in the last lesson that
draws a straight line on the screen. +e could use this instruction three times to draw a simple
triangle.
&etter still, we could define a method to call this instruction three times and draw the triangle.
+e would call the method triangle, presumably, and wheneer we wanted a triangle drawn, we
would call the method.
8eople who hae come to Baa from other programming languages will almost certainly hae
recognised this by now. "he idea of methods appears in all programming languages, although
sometimes it goes under the name functions and sometimes under the name procedures. "he
name methods is a throw-back to the language 4AA, from which Baa was deeloped. 'n 4AA,
there is an object called a class which can contain methods. 2oweer, you will hae noticed that
eerything in Baa is enclosed within a class of some sort $after all, the program contains the
instruction public cla e!tend Applet%, so the functions within it are called methods.
Creating a method in a Java program
2ere is an example of a simple method called calculation. "he method is defined in a ery
similar way to paint"# $indeed, paint"# is a method, except it is called automatically by the Baa
system%.
i$port %a&a'a(t')*
i$port %a&a'applet')*
public cla calculation e!tend Applet
+ int ,irt- an(er*
public &oid paint ".raphic g#
+ ,irt / 01*
calculation"#*
g'dra(String"2T(ice 01 i 2 3 an(er- 45- 67#*
8
public &oid calculation "#
+ an(er / ,irt ) 6*
8
8
"he method is called by the statement calculation"#*. 0ou'll notice that we hae to put a pair of
brackets after the name, een though there is nothing between them, and that we do, of course,
need the semicolon at the end.
Bust calling the method isn't enough. 't has to be defined somewhere, or Baa will not know
exactly what to do when it comes across the calculation"#* command. "he definition starts with
either the word public or pri&ate $at the moment, it doesn't matter which of these you use - we
will be going into these in more detail in a later section%, followed by the method name
$calcuation in this case% and the pair of brackets again.
On the next line we hae an open curly bracket followed by the statements that make up the
method. 'n this case, we only hae one statement - the one that sets up the alue of an(er. "hen
we hae a closing curly bracket to show that we are at the end of the method.
4alling the method calculation"# is e)uialent to executing the statement an(er / ,irt ) 6. 'n
this case, it is hardly worth defining a method to carry out one simple instruction. 2oweer, it
does show the minimum needed for a method to be defined in a program.
. common mistake - and one that ' am always makingI - is forgetting the closing curly bracket at
the end of the method definition. 2ere is the same definition that you saw aboe but with a
deliberate mistake:
i$port %a&a'a(t')*
i$port %a&a'applet')*
public cla calculation e!tend Applet
+ int ,irt- an(er*
public &oid paint ".raphic g#
+ ,irt / 01*
calculation"#*
g'dra(String"2T(ice 01 i 2 3 an(er- 45- 67#*
8
public &oid calculation "#
+ an(er / ,irt ) 6* 8
2ere, ' hae missed out the ending bracket. 2oweer, Baa spots that there is an ending bracket
afterwards and assumes that this is the one that ends the method definition. 't then looks round
for an ending bracket to end the class, doesn't find it, and produces an error message. "his is why
it is useful to indent your program lines in a similar way to mine, so that you can spot
immediately when there is a bracket missing.
void
0ou will hae noticed that there was an extra word just after the word public, namely the word
&oid.
"he word after the public or pri&ate $i.e. the second word of the method declaration% is the
return type of the method. +e will be dealing with alues returned from methods in the next
section, so ' don't want to say much about them here. "he word &oid in this case indicates that
the method does not return a number or a alue.
'f you want to call a method using a simple instruction $as in the case of the method
calculation"# aboe%, then you should include the word &oid after the word public or pri&ate.
Parameters
"he following program shows a Baa program with a method to draw a triangle:
i$port %a&a'a(t')*
i$port %a&a'applet')*
public cla triangle9e$o e!tend Applet
+
public &oid paint ".raphic g#
+ triangle"g#*
8
public &oid triangle ".raphic $:;graphic#
+ $:;graphic'dra(Line"455- 455- 475- 455#*
$:;graphic'dra(Line"475- 455- 467- 475#*
$:;graphic'dra(Line"467- 475- 455- 455#*
8
8
Meage
. single object alone is generally not ery useful and usually appears as a component of a larger
program or application that contains many other objects. "hrough the interaction of these objects,
programmers achiee higher order functionality and more complex behaior. 0our bicycle
hanging from a hook in the garage is just a bunch of titanium alloy and rubber/ by itself the
bicycle is incapable of any actiity. "he bicycle is useful only when when another object $you%
interacts with it $starts pedaling%.
1oftware objects interact and communicate with each other by sending messages to each other.
+hen object . wants object & to perform one of &'s methods, object . sends a message to object
&.
1ometimes the receiing object needs more information so that it knows exactly what to do--for
example, when you want to change gears on your bicycle, you hae to indicate which gear you
want. "his information is passed along with the message as parameters.
"hree components comprise a message:
6. "he object to whom the message is addressed $0our &icycle%
E. "he name of the method to perform $change?ears%
H. .ny parameters needed by the method $lower gear%
"hese three components are enough information for the receiing object to perform the desired
method. Jo other information or context is re)uired.
The Bene,it o, Meage
.n object's behaior is expressed through its methods, so $aside from direct ariable
access% message passing supports all possible interactions between objects.
Objects don't need to be in the same process or een on the same machine to send and
receie messages back and forth to each other.
ABSTACTION AN9 ENCA<SULATION
.bstraction is simplifying complex reality by modelling classes appropriate to the
problem, and working at the most appropriate leel of inheritance for a gien aspect of the
problem. (or example, Lassie the #og may be treated as a #og much of the time, a 4ollie when
necessary to access 4ollie-specific attributes or behaiors, and as an .nimal $perhaps the parent
class of #og% when counting "immy's pets.
9ncapsulation conceals the functional details of a class from objects that send messages
to it. (or example, the #og class has a bark$% method. "he code for the bark$% method defines
exactly how a bark happens $e.g., by inhale$% and then exhale$%, at a particular pitch and olume%.
"immy, Lassie's friend, howeer, does not need to know exactly how she barks. 9ncapsulation is
achieed by specifying which classes may use the members of an object. "he result is that each
object exposes to any class a certain interface - those members accessible to that class. "he
reason for encapsulation is to preent clients of an interface from depending on those parts of the
implementation that are likely to change in future, thereby allowing those changes to be made
more easily, that is, without changes to clients. (or example, an interface can ensure that puppies
can only be added to an object of the class #og by code in that class. -embers are often
specified as public, protected or priate, determining whether they are aailable to all classes,
sub-classes or only the defining class. 1ome languages go further: Baa uses the default access
modifier to restrict access also to classes in the same package, 4K and =&.J9" resere some
members to classes in the same assembly using keywords internal $4K% or (riend $=&.J9"%, and
9iffel and 4AA allow one to specify which classes may access any member.
Inheritance
#ifferent kinds of objects often hae a certain amount in common with each other. -ountain
bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles $current
speed, current pedal cadence, current gear%. 0et each also defines additional features that make
them different: tandem bicycles hae two seats and two sets of handlebars/ road bikes hae drop
handlebars/ some mountain bikes hae an additional chain ring, giing them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behaior from
other classes. 'n this example, &icycle now becomes the superclass of -ountain&ike, !oad&ike,
and "andem&ike. 'n the Baa programming language, each class is allowed to hae one direct
superclass, and each superclass has the potential for an unlimited number of subclasses:
. hierarchy of bicycle classes.
"he syntax for creating a subclass is simple. .t the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
class -ountain&ike e!tend &icycle :
77 new fields and methods defining a mountain bike would go here
>
"his gies -ountain&ike all the same fields and methods as &icycle, yet allows its code to focus
exclusiely on the features that make it uni)ue. "his makes code for your subclasses easy to
read. 2oweer, you must take care to properly document the state and behaior that each
superclass defines, since that code will not appear in the source file of each subclass.
Abtract clae
"here are situations in which you will want to define a superclass that declares the structure of
a gien abstraction without proiding a complete implementation of eery method. "hat is,
sometimes you will want to create a superclass that only defines a generaliLed form that will be
shared by all of its subclasses, leaing it to each subclass to fill in the details. 1uch a class
determines the nature of the methods that the subclasses must implement. One way this situation
can occur is when a superclass is unable to create a meaningful implementation for a method.
"his is the case with the class =igure used in the preceding example. "he definition of area" # is
simply a placeholder. 't will not compute and display the area of any type of object.
.s you will see as you create your own class libraries, it is not uncommon for a method to
hae no meaningful definition in the context of its superclass. 0ou can handle this situation
two ways. One way, as shown in the preious example, is to simply hae it report a warning
message. +hile this approach can be useful in certain situations3such as debugging3it is not
usually appropriate. 0ou may hae methods which must be oerridden by the subclass in order
for the subclass to hae any meaning. 4onsider the class Triangle. 't has no meaning if area" #
is not defined. 'n this case, you want some way to ensure that a subclass does, indeed, oerride
all necessary methods. Baa's solution to this problem is the abstract method.
0ou can re)uire that certain methods be oerridden by subclasses by specifying the abtract
type modifier. "hese methods are sometimes referred to as subclasser responsibility because
they hae no implementation specified in the superclass. "hus, a subclass must oerride them
3it cannot simply use the ersion defined in the superclass. "o declare an abstract method,
use this general form:
abstract type name(parameter-list)/
2ere is a simple example of a class with an abstract method, followed by a class which
implements that method:
>> A Si$ple de$ontration o, abtract'
abtract cla A +
abtract &oid call$e"#*
>> concrete $ethod are till allo(ed in abtract clae
&oid call$etoo"# +
S:te$'out'println"2Thi i a concrete $ethod'2#*
8
8
cla B e!tend A +
&oid call$e"# +
S:te$'out'println"2B? i$ple$entation o, call$e'2#*
8
8
cla Abtract9e$o +
public tatic &oid $ain"String arg@A# +
B b / ne( B"#*
b'call$e"#*
b'call$etoo"#*
8
8
Jotice that no objects of class A are declared in the program. .s mentioned, it is not possible
to instantiate an abstract class. One other point: class A implements a concrete method called
call$etoo" #. "his is perfectly acceptable. .bstract classes can include as much
implementation as they see fit.
<ol:$orphi$
?enerally, the ability to appear in many forms. 'n object-oriented programming,
polymorphism refers to a programming language's ability to process objects differently
depending on their data type or class. -ore specifically, it is the ability to redefine methods for
derived classes. (or example, gien a base class shape, polymorphism enables the programmer
to define different area methods for any number of deried classes, such as circles, rectangles
and triangles. Jo matter what shape an object is, applying the area method to it will return the
correct results. 8olymorphism is considered to be a re)uirement of any true object-oriented
programming language $OO8L%.
6% . ariable with a gien name may be allowed to hae different forms and the program can
determine which form of the ariable to use at the time of execution. (or example, a ariable
named @19!'# may be capable of being either an integer $whole number% or a string of
characters $perhaps because the programmer wants to allow a user to enter a user '# as either an
employee number - an integer - or with a name - a string of characters%. &y giing the program a
way to distinguish which form is being handled in each case, either kind can be recogniLed and
handled.
E% . named function can also ary depending on the parameters it is gien. (or example, if gien
a ariable that is an integer, the function chosen would be to seek a match against a list of
employee numbers/ if the ariable were a string, it would seek a match against a list of names. 'n
either case, both functions would be known in the program by the same name. "his type of
polymorphism is sometimes known as oerloading.
Clae and Ob%ect in %a&a
(ollowing is the code for a class called 1imple8oint that represents a point in E# space:
public class 1imple8oint :
public int x ; </
public int y ; </
>
"his segment of code declares a class-- a new data type really-- called 1imple8oint. "he
1imple8oint class contains two integer member variables, x and y. "he public keyword
preceding the declaration for x and y means that any other class can freely access these two
members.
0ou create an object from a class such as 1imple8oint by instantiating the class. +hen you create
a new 1imple8oint object $we show you how shortly%, space is allocated for the object and its
members x and y. 'n addition, the x and y members inside the object are initialiLed to < because
of the assignment statements in the declarations of these two members.
Jow, here's a class, 1imple!ectangle, that represents a rectangle in E# space:
public class 1imple!ectangle :
public int width ; </
public int height ; </
public 1imple8oint origin ; new 1imple8oint$%/
>
"his segment of code declares a class $another data type%--1imple!ectangle-- that contains two
integer members, width and height. 1imple!ectangle also contains a third member, origin, whose
data type is 1imple8oint. Jotice that the class name 1imple8oint is used in a ariable declaration
as the ariable's type. 0ou can use the name of a class anywhere you can use the name of a
primitie type.
"his diagram shows the difference between primitie types and reference types. &oth width and
height are integers and are fully contained within 1imple!ectangle. On the other hand, origin
simply references a 1imple8oint object somewhere else. "he 1imple8oint and 1imple!ectangle
classes as shown are simplistic implementations for these classes. &oth should proide a
mechanism for initialiLing their members to alues other than <. .dditionally, 1imple!ectangle
could proide a method for computing its area, and because 1imple!ectangle creates a
1imple8oint when it's created, the class should proide for the clean up of the 1imple8oint when
1imple!ectangle gets cleaned up. 1o, here's a new ersion of 1imple8oint, called 8oint, that
contains a constructor which you can use to initialiLe a new 8oint to a alue other than $<,<%:
public class 8oint :
public int x ; </
public int y ; </
77 a constructorI
public 8oint$int x, int y% :
this.x ; x/
this.y ; y/
>
>
Jow, when you create a 8oint, you can proide initial alues for it like this:
new 8oint$GG, MN%
"he alues GG and MN are passed into the constructor and subse)uently assigned to the x and y
members of the new 8oint object as shown here:
Jow, let's beef up the 1imple!ectangle class. 2ere's a new ersion of 1imple!ectangle, called
!ectangle, that contains four constructors, a method to *moe* the rectangle, a method to
compute the area of the rectangle, and a finaliLe method to proide for clean up:
public class !ectangle :
public int width ; </
public int height ; </
public 8oint origin/
77 four constructors
public !ectangle$% :
origin ; new 8oint$<, <%/
>
public !ectangle$8oint p% :
origin ; p/
>
public !ectangle$int w, int h% :
this$new 8oint$<, <%, w, h%/
>
public !ectangle$8oint p, int w, int h% :
origin ; p/
width ; w/
height ; h/
>
77 a method for moing the rectangle
public oid moe$int x, int y% :
origin.x ; x/
origin.y ; y/
>
77 a method for computing the area of the rectangle
public int area$% :
return width O height/
>
77 clean upI
protected oid finaliLe$% throws "hrowable :
origin ; null/
super.finaliLe$%/
>
>
Creating Ob%ect
'n Baa, you create an object by creating an instance of a class or, in other words, instantiating a
class. Often, you will see a Baa object created with a statement like the following, which creates
a new !ectangle object from the !ectangle class gien in the preious section:
!ectangle rect ; new !ectangle$%/
"his single statement performs three actions:
6. 9eclaration: !ectangle rect is a ariable declaration that declares to the compiler that the
name rect will be used to refer to a !ectangle object. Jotice that a class name is used as
the ariable's type.
E. Intantiation: new is a Baa operator that creates the new object $allocates space for it%.
H. InitialiBation: !ectangle$% is a call to !ectangle's constructor, which initialiLes the
object.
9eclaring an Ob%ect
"he declaration of an object is not a necessary part of object creation, although it often appears
on the same line. Like other ariable declarations, object declarations can also appear alone, like
this:
!ectangle rect/
=ariables and #ata "ypes in the preious lesson discussed ariable declarations in detail. "o
declare an object, you just follow the same rules and declare a ariable to refer to that object by
declaring its type and name:
type name
'n Baa, classes and interfaces can be used as data types. 1o type can be the name of a class such
as the !ectangle class or the name of an interface. 4lasses and interfaces are both reference types
$the ariable's actual alue is a reference to the alue or set of alues represented by the
ariable%. 'n this tutorial, a reference may also be called an object reference or an array
reference, depending on the data to which the reference refers.
#eclarations notify the compiler that you will use name to refer to a ariable whose type is type.
9eclaration do not create ne( ob%ect' !ectangle rect does not create a new !ectangle object,
just a ariable named rect to hold a !ectangle object. "o create a !ectangle object, or any other
object, use the new operator.
Intantiating an Ob%ect
"he new operator instantiates a class by allocating memory for a new object of that type. new
re)uires a single, postfix argument: a call to a constructor. 9ach Baa class proides a set of
constructors used to initialiLe new objects of that type. "he new operator creates the object, and
the constructor initialiLes it. 2ere's an example of using the new operator to create a !ectangle
object:
new !ectangle$6<<, E<<%/
2ere, !ectangle$6<<, E<<% is the argument to new. "he new operator returns a reference to the
newly created object. "his reference can be assigned to a ariable of the appropriate type, as
shown here.
!ectangle rect ; new !ectangle$6<<, E<<%/
.fter this statement, rect refers to a !ectangle object whose origin is at $<, <%, width is 6<<, and
height is E<<.
Acce Speci,ier
One of the techni)ues in object-oriented programming is encapsulation. 't concerns the hiding of
data in a class and making this class aailable only through methods. 'n this way the chance of
making accidental mistakes in changing alues is minimiLed. Baa allows you to control access
to classes, methods, and fields ia so-called access specifiers.
Baa offers four access specifiers, listed below in decreasing accessibility:
public
protected
default $no specifier%
priate
public
public classes, methods, and fields can be accessed from eerywhere. "he only constraint is that
a file with Baa source code can only contain one public class whose name must also match with
the filename. 'f it exists, this public class represents the application or the applet, in which case
the public keyword is necessary to enable your +eb browser or appletiewer to show the applet.
0ou use public classes, methods, or fields only if you explicitly want to offer access to these
entities and if this access cannot do any harm. .n example of a s)uare determined by the position
of its upper-left corner and its siLe:
public class 1)uare : 77 public class
public x, y, siLe/ 77 public instance ariables
>
Protected
protected methods and fields can only be accessed within the same class to which the methods
and fields belong, within its subclasses, and within classes of the same package, but not from
anywhere else. 0ou use the protected access leel when it is appropriate for a class's subclasses
to hae access to the method or field, but not for unrelated classes.
default (no specifier)
'f you do not set access to specific leel, then such a class, method, or field will be accessible
from inside the same package to which the class, method, or field belongs, but not from outside
this package. "his access-leel is conenient if you are creating packages. (or example, a
geometry package that contains 1)uare and "iling classes, may be easier and cleaner to
implement if the coordinates of the upper-left corner of a 1)uare are directly aailable to the
"iling class but not outside the geometry package.
private
priate methods and fields can only be accessed within the same class to which the methods and
fields belong. priate methods and fields are not isible within subclasses and are not inherited
by subclasses. 1o, the priate access specifier is opposite to the public access specifier. 't is
mostly used for encapsulation: data are hidden within the class and accessor methods are
proided. .n example, in which the position of the upper-left corner of a s)uare can be set or
obtained by accessor methods, but indiidual coordinates are not accessible to the user.
public class 1)uare : 77 public class
priate double x, y 77 priate $encapsulated% instance ariables
public set4orner$int x, int y% : 77 setting alues of priate fields
this.x ; x/
this.y ; y/
>
public get4orner$% : 77 setting alues of priate fields
return 8oint$x, y%/
>
>
Static Me$ber
'n addition to $instance% members, a Baa class can include static members that are
attached to the class rather than instances of the class. +e hae already seen how static final
fields proide a simple way to define constants.
"he static members of a class are not included in the template used to create class
instances. "here is only one copy of a static field for an entire class--regardless of how many
instances of the class are created $possibly none%. 1imilarly, the code in a static method cannot
refer to this or to the fields of this because there is no class instance to sere as the receier for
such an access.7footnoteOf course, a static method can inoke an instance method $or extract an
instance field% of class if it explicitly specifies a receier for the inocation.
1tatic methods are useful because we occasionally need to write methods where the
primary argument is either a primitie alue or an object from a class that we cannot modify. (or
example, the library method 'nteger.to1tring$int i% conerts an int to the corresponding 1tring.
1ince an int is not an object, there is no int class to hold such a method.
6.M
4onse)uently, the Baa
library proides a static method to1tring$int i% in the class 'nteger.
1imilarly, an operation
public 1tring s)ueeLe+hite1pace$1tring s%/
that returns a 1tring identical to s with all spaces and tabs remoed should be expressed as a
static method because the 1tring class cannot be modified or extended.
(inally, all operations on arrays must be expressed in static $procedural% form because array
types do not hae conentional class definitions/ they are built-in to the Baa irtual machine. +e
will discuss arrays in 4hapter E when we address imperative programming in Baa.
class -y@tils :
. . .
77;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mean
public tatic double mean$intCD p% :
int sum ; </ 77 sum of all the elements
for $int i;</ iPp.length/ iAA% :
sum A; pCiD/
>
return $$double%sum% 7 p.length/
>77endmethod mean
. . .
>
Contructor
+hen you create a new instance $a new object% of a class using the new keyword, a
constructor for that class is called. 4onstructors are used to initialiLe the instance ariables
$fields% of an object. 4onstructors are similar to methods, but with some important differences.
Contructor na$e i cla na$e. . constructors must hae the same name as the class
its in.
9e,ault contructor. 'f you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler. "he default constructor calls the
default parent constructor $super$%% and initialiLes all instance ariables to default alue
$Lero for numeric types, null for object references, and false for booleans%.
9e,ault contructor i created onl: i, there are no contructor. 'f you define any
constructor for your class, no default constructor is automatically created.
9i,,erence bet(een $ethod and contructor.
o "here is no return type gien in a constructor signature $header%. "he alue is this
object itself so there is no need to indicate a return alue.
o "here is no return statement in the body of the constructor.
o "he first line of a constructor must either be a call on another constructor in the
same class $using this%, or a call on the superclass constructor $using super%. 'f the
first line is neither of these, the compiler automatically inserts a call to the
parameterless super class constructor.
"hese differences in syntax between a constructor and method are sometimes hard to see
when looking at the source. 't would hae been better to hae had a keyword to clearly
mark constructors as some languages do.
thi"'''# - Call another contructor in a$e cla. Often a constructor with few
parameters will call a constructor with more parameters, giing default alues for the
missing parameters. @se this to call other constructors in the same class.
uper"'''#. @se super to call a constructor in a parent class. 4alling the constructor for the
superclass must be the first statement in the body of a constructor. 'f you are satisfied
with the default constructor in the superclass, there is no need to make a call to it because
it will be supplied automatically.

Example of explicit this constructor call


public class 8oint :
int mQx/
int mQy/
77;;;;;;;;;;;; 4onstructor
public 8oint$int x, int y% :
mQx ; x/
mQy ; y/
>
77;;;;;;;;;;;; 8arameterless default constructor
public 8oint$% :
thi$<, <%/ 77 4alls other constructor.
>
. . .
>
super(...) - The superclass (parent) constructor
.n object has the fields of its own class plus all fields of its parent class, grandparent class, all
the way up to the root class Object. 't's necessary to initialiLe all fields, therefore all constructors
must be calledI "he Baa compiler automatically inserts the necessary constructor calls in the
process of constructor chaining, or you can do it explicitly.
"he Baa compiler inserts a call to the parent constructor $super% if you don't hae a constructor
call as the first statement of you constructor. "he following is the e)uialent of the constuctor
aboe.
77;;;;;;;;;;;; 4onstructor $same as in aboe example%
public 8oint$int x, int y% :
uper"#* 77 .utomatically done if you don't call constructor here.
mQx ; x/
mQy ; y/
>
=inaliBe $ethod
protected &oid ,inaliBe"# thro( Thro(able +8
eery class inherits the ,inaliBe"# method from %a&a'lang'Ob%ect
the method is called by the garbage collector when it determines no more references to
the object exist
the Ob%ect finaliLe method performs no actions but it may be oerridden by any class
normally it should be oerridden to clean-up non-Baa resources ie closing a file
if oerridding finaliLe$% it is good programming practice to use a tr:-catch-,inall:
statement and to always call uper',inaliBe"# "J<L pg 1C-1D#. "his is a saftey measure
to ensure you do not inadertently miss closing a resource used by the objects calling
class
protected &oid ,inaliBe"# thro( Thro(able +
tr: +
cloe"#* >> cloe open ,ile
8 ,inall: +
uper',inaliBe"#*
8
8
any e!ception thrown by ,inaliBe"# during garbage collection halts the finaliLation but
is otherwise ignored
,inaliBe"# is ne&er run $ore than once on any object

Das könnte Ihnen auch gefallen