Você está na página 1de 6

A Java program is mostly a collection of objects talking to other objects by invoking

each other's methods.


Class A template that describes the kinds of state and behavior that objects
of its type support.
Object At runtime, when the Java Virtual Machine JVM! encounters the
new keyword, it will use the appropriate class to make an object which is an
instance of that class. "hat object will have its own state, and access to all of
the behaviors de#ned by its class.
State instance variables! $ach object instance of a class! will have its
own uni%ue set of instance variables as de#ned in the class. &ollectively, the
values assigned to an object's instance variables make up the object's state.
Behavior methods! 'hen a programmer creates a class, she creates methods
for that class. Methods are where the class' logic is stored. Methods are
where the real work gets done. "hey are where algorithms get e(ecuted, and
data gets manipulated.
Legal Identifers
"echnically, legal identi#ers must be composed of only )nicode characters,
numbers, currency symbols, and connecting characters like underscores!. "he
e(am doesn't dive into the details of which ranges of the )nicode character set are
considered to %ualify as letters and digits. *o, for e(ample, you won't need to know
that "ibetan digits range from \u0420 to \u0f29. +ere are the rules you do need
to know,
-denti#ers must start with a letter, a currency character .!, or a connecting
character such as the underscore / !. -denti#ers cannot start with a number0
After the #rst character, identi#ers can contain any combination of letters,
currency characters, connecting characters, or numbers.
-n practice, there is no limit to the number of characters an identi#er can
contain.
1ou can't use a Java keyword as an identi#er. "able 232 lists all of the Java
keywords including one new one for 4.5, enum.
-denti#ers in Java are case3sensitive6 foo and FOO are two di7erent identi#ers.
$(amples of legal and illegal identi#ers follow, #rst some legal identi#ers,
int _a;
int $c;
int ______2_w;
int _$;
int this_is_a_very_detailed_name_for_an_identifier;
abstract boolean break byte case catch
char class const continue default do
double else extends final finally float
for goto if implements import instanceof
int interface long native new package
private protected public return short static
strictfp super switch synchronized this throw
throws transient try void volatile while
assert enum
Declare Classes:
8efore we dig into class declarations, let's do a %uick review of the rules associated
with declaring classes, import statements, and package statements in a source #le,
"here can be only one public class per source code #le.
&omments can appear at the beginning or end of any line in the source code
#le6 they are independent of any of the positioning rules discussed here.
-f there is a public class in a #le, the name of the #le must match the name
of the public class. 9or e(ample, a class declared as public class Dog { }
must be in a source code #le named Dog.java.
-f the class is part of a package, the package statement must be the #rst line
in the source code #le, before any import statements that may be present.
-f there are import statements, they must go between the package statement
if there is one! and the class declaration. -f there isn't a package statement,
then the import statements! must be the #rst lines! in the source code #le.
-f there are no package or import statements, the class declaration must be
the #rst line in the source code #le.
import and package statements apply to all classes within a source code #le.
-n other words, there's no way to declare multiple classes in a #le and have
them in di7erent packages, or use di7erent imports.
A #le can have more than one nonpublic class.
*ource 9ile :eclaration ;ules
9iles with no public classes can have a name that does not match any of the
classes in the #le.
Declare Interfaces
'hen you create an interface, you're de#ning a contract for what a class can do,
without saying anything about how the class will do it. An interface is a contract.
1ou could write an interface Bounceable, for e(ample, that says in e7ect, <"his is
the Bounceable interface. Any class type that implements this interface must agree
to write the code for the bounce() and setBounceFactor() methods.<
public interface Bounceable {
void bounce(); // No modifiers
void setBounceFactor(int bf); // No modifiers
}
"hese rules are strict,
All interface methods are implicitly public and abstract. -n other words,
you do not need to actually type the public or abstract modi#ers in the
method declaration, but the method is still always public and abstract.
All variables de#ned in an interface must be public, static, and final=
in other words, interfaces can declare only constants, not instance variables.
-nterface methods must not be static.
8ecause interface methods are abstract, they cannot be marked final,
strictfp, or native. More on these modi#ers later.!
An interface can extend one or more other interfaces.
An interface cannot e(tend anything but another interface.
An interface cannot implement another interface or class.
An interface must be declared with the keyword interface.
-nterface types can be used polymorphically
;anges of >umeric ?rimitives
Type Bits Bytes inim!m "ange a#im!m"angType Bits Bytes inim!m
"ange a#im!m "ange
byte @ 2 -AB AB-2
short 2C A -A24 A24-2
int DA E -AD2 AD2-2
long CE @ -ACD ACD-2
float DA E nFa nFa
double CE @ nFa nFa
Declaring "eference $ariables
;eference variables can be declared as static variables, instance variables, method
parameters, or local variables. 1ou can declare one or more reference variables,
of the same type, in a single line. -n &hapter D we will discuss the various ways in
which they can be initialiGed, but for now we'll leave you with a few e(amples of
reference variable declarations,
Object o;
Dog myNewDogReferenceVariable;
String s1, s2, s3; // declare three String vars.
Instance $ariables
-nstance variables are de#ned inside the class, but outside of any method, and
are only initialiGed when the class is instantiated. -nstance variables are the #elds
that belong to each uni%ue object. 9or e(ample, the following code de#nes #elds
instance variables! for the name, title, and manager for employee objects,
class Employee {
// define fields (instance variables) for employee instances
private String name;
private String title,
private String manager;
// other code goes here including access methods for private
// fields
}
table %&'
Inheritance( Is&)( *as&)
IS&) and *)S&) "elationships
-n HH, the concept of -*3A is based on class inheritance or interface
implementation. -*3A is a way of saying, <this thing is a type of that thing.< 9or
e(ample, a Mustang is a type of horse, so in HH terms we can say, <Mustang -*3A
+orse.< *ubaru -*3A &ar. 8roccoli -*3A Vegetable not a very fun one, but it still
counts!. 1ou e(press the -*3A relationship in Java through the keywords extends
for class inheritance! and implements for interface implementation!.
public class Vehicle { ... }
public class Car extends Vehicle { ... }
public class Subaru extends Car { ... }
*)S&)
+A*3A relationships are based on usage, rather than inheritance. -n other words,
class A +A*3A 8 if code in class A has a reference to an instance of class 8. 9or
e(ample, you can say the following,
A +orse -*3A Animal. A +orse +A*3A +alter.
"he code might look like this,
public class Animal { }
public class Horse extends Animal {
private Halter myHalter;
}
Overriding + Overloading
Overloading deals with multiple methods in the same class
with the same name but different method signatures.
class MyClass {
public void getInvestAmount(int rate) {}
public void getInvestAmount(int rate long principal)
{ }
}
!oth the above methods have the same method names
but different method signatures which mean the methods
are overloaded.
Overriding deals with two methods one in the parent class and
the other one in the child class and has the same name and
signatures.
class BaseClass{
public void getInvestAmount(int rate) {}
}
class MyClass extends BaseClass {
public void getInvestAmount(int rate) { }
}
!oth the above methods have the same method names and
the signatures but the method in the subclass MyClass
overrides the method in the superclass BaseClass.
The Calendar Class and Date class
import java.util.*;
class Dates2 {
public static void main(String[] args) {
Date d1 = new Date(1000000000000L);
System.out.println("1st date " + d1.toString());
Calendar c = Calendar.getInstance();
c,setTime-d%./ ++ 0%
if-c,S12D)3 44 c,get5irstDayOf6ee7-.. ++ 08
System.out.println("Sunday is the first day of the week");
System.out.println("trillionth milli day of week is "
+ c,get-c,D)39O596::;../ ++ 0'
c,add-Calendar,O2T*( %./ ++ 0<
Date d8 4 c,getTime-./ ++ 0=
System.out.println("new date " + d2.toString() );
}
}
"his produces something like
1st date Sat Sep 08 19:46:40 MDT 2001
Sunday is the first day of the week
trillionth milli day of week is 7
new date Mon Oct 08 20:46:40 MDT 2001
The Date5ormat Class
import java.text.*;
import java.util.*;
class Dates3 {
public static void main(String[] args) {
Date d1 = new Date(1000000000000L);
DateFormat[] dfa = new DateFormat[6];
dfa[0] = DateFormat.getInstance();
dfa[1] = DateFormat.getDateInstance();
dfa[2] = DateFormat.getDateInstance(DateFormat.SHORT);
dfa[3] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dfa[4] = DateFormat.getDateInstance(DateFormat.LONG);
dfa[5] = DateFormat.getDateInstance(DateFormat.FULL);
for(DateFormat df : dfa)
System.out.println(df.format(d1));
}
}
which on our JVM produces
9/8/01 7:46 PM
Sep 8, 2001
9/8/01
Sep 8, 2001
September 8, 2001
Saturday, September 8, 2001
Methods of &lass Hbject
boolean equals (Object
obj)
:ecides whether two objects are meaningfully e%uivalent.
void finalize() &alled by garbage collector when the garbage collector sees that the
object cannot be referenced.
int hashCode() ;eturns a hashcode int value for an object, so that the object can
be used in &ollection classes that use hashing, including +ashtable,
+ashMap, and +ash*et.
final void notify() 'akes up a thread that is waiting for this objectIs lock.
final void notifyAll() 'akes up all threads that are waiting for this objectIs lock.
final void wait() &auses the current thread to wait until another thread calls
notify() or notifyAll() on this subject.
String toString() ;eturns a Jte(t representationK of the object.table >&%
table >&%

Você também pode gostar