java 程序设计 java 程序设计 java programming spring, 2013
TRANSCRIPT
-
Java Java ProgrammingSpring, 2013
-
Chapter 4: Classes & ObjectsClass Declaration Class Modifiers Class Members Class Fields Object Creation Fields Initilazation Methods Package
-
Class Declaration ()The class is the fundamental programming unit of the Java programming language.Classes provide the structure for objects and the mechanisms to manufacture objects from a class definition.
Each object is an instance of a class.A program is defined by using one or more classes.
-
Class Declaration ()Example:
class Body {public long idNum;public String name;public Body orbits;
public static long nextID = 0;}
-
Class DeclarationSyntax():
class is a keyword for class declaration. When the compiler sees the word class, it understands that the word after class is the name for the class;The first letter of the name for the class must be a Unicode letter or underline _ . class ClassName { Declarations of class members }
-
Class Modifier ()Modifiers are reserved words to specify the properties of the data, methods, and classes and how they can be used.
Class modifier:public a public class is publicly accessible. Without this modifier a class is only accessible within its own package.abstract used to declare an abstract class. final a final class cannot be subclassed.strictfp Strict floating point , a strictfp class has all floating-point arithmetic, defined within the class, evaluated strictly.
-
Class Modifier ()A class declaration can be modified by several modifiers, and modifiers are allowed in any order.
A class cannot be both final and abstract!(Why?)
-
Class Members ()Fields the data variables associated with a class and its objects, which hold the state of the class or object;Methods contains the executable code of a class and define the behavior of objects.Nested classes & nested interfaces ()classes or interfaces declared within the declaration of another class or interface.
-
Fields ()Syntax(): ; = ;
class Body {public long idNum;public String name;public Body orbits;
public static long nextID = 0;}
-
Field Types () boolean char byte, short, int, long float, double
-
Modifier of FieldsAccess modifier ()private accessible only in the class in which it is declared;package members with no access modifier are accessible in classes in the same package; protected accessible in subclasses of the class and in the class itself. public accessible anywhere the class is accessible.
-
Modifier of Fieldsstatic to declare class variable shared by all objects of a class;final a final variable cannot be changed after it has been initialized;transient transient(, ) variable cannot be serialized;volatile a read of volatile variable by different threads always returns the most recent value.
A field cannot be both final & volatile!
-
final Fields()final The value of a final variable cannot be changed after it has been initialized.used to define an immutable() property which doesnt change for the lifetime of a class or object.
-
Fields ()static
()static
-
Field Initialization ()When a field is declared, it can be initialized by assigning it a value of the corresponding right type.Initializer() can be:a constant, another field, a method invocation, or an expression.
-
Field Initialization ()Example:
double zero = 0.0; //constantdouble sum = 4.5 + 3.; //constant expressiondouble zeroCopy = zero; //fielddouble rootTwo = Math.sqrt(2); //method invocationdouble someVal = sum + 2*Math.sqrt(rootTwo); //mixed
-
Field Initialization ()Default() InitializationIf a field is not initialized, a default initial value is assigned to it depending on its type.
-
//Student.java
class Student{ String name = zhang;// String stuNumber; name=zhang; // void setBase(String s1, String s2){ name=s1; stuNumber=s2; System.out.println(name+" "+stuNumber); }
}
-
Initialization Blocks ()A block of statement that appears within the class declaration, outside of anything else of the class;To perform complex initialization of fields;It is executed at the beginning of every constructor in the class;Example: {idNum = nextID++;}
-
Initialization Blocks ()class Body{ public long idNum; public String name=; public Body orbits=null; public static long nextID=0;
//Initialization Blocks () {idNum=nextID++; }
Body(String name){ this.name=name; }}
-
Class Variables/Static Fields/A static field shared by all objects of a class;only one copy of the field exists.Declaration: static type
public class Circle {static double PI = 3.14159; //Static fieldint radius;}
-
/radius CircleOne copy for each instanceOne copy for class Circle
-
Static Initialization Block()Only be used to initialize static variables;A static initialization block is declared static in the form of a non-static initialization block;The static initializers are executed when the class is loaded;
-
Static Initialization Block() class Evens{ static int[] evens;
static{ //Static Initialization block () evens = new int[4];
evens[0]=0; for(int i=1;i
-
Class Variables/Static Fields/Access():Within its own class a static field can be referred to directly;When accessed externally it must be accessed via the class name.
System.out.println(Circle.PI); not recommendedCircle circle=new Circle();System.out.println(circle.PI);
-
//static:Stu.java, Student.javaclass Student{ String name, stuNumber; double score1, score2, score3;static int count= 0;//
void setBase(String s1,String s2) { name=s1; stuNumber=s2; System.out.println(name+" " + stuNumber); }}public class Stu{ public static void main(String args[]){Student s1=new Student( ); //s1.count++; //System.out.println(s1.count);Student s2=new Student( );s2.count++; //System.out.println(Student.count); // }}12
-
Constructors ()a class can have more than one constructor;have the same name as the class;take zero or more arguments;can be used to initialize an object;like method with no return type.
-
Example:class Point{int x,y;Point() //no-arg constructor {}Point(int a, int b){ //Constructor with arguments x=a; y=b;}}
-
ConstructorsDefault() constructorconstructor with no arguments are called no-arg constructors (); Java system automatically provides a default no-arg constructor that does nothing if the programmer doesnt provide any constructors;If both a no-arg constructor and one or more constructors with arguments are wanted in a class, the programmer must explicitly provide a no-arg constructor.
-
Exampleclass Point{ int x, y;}
Point p = new Point( );How to create an object of Point?
-
//class Point {int x,y;
Point(int a,int b){x=a;y=b;}}public class A {public static void main(String args[ ]) {Point p1,p2;p1=new Point(10,10);p2=new Point();}}// ?
-
ConstructorsExplicit constructor invocation () : this() invokes() another constructor from the same class as its first executable statement;
The type and number of arguments are used to determine which constructor gets invoked.class Body{ . Body(){ idNum=nextID++; }
Body(String name){ this( ); //must be at the first line this.name=name; }}
-
this :
class Point{int x,y,z;Point(){ }Point(int a,int b){x=a;y=b;}
Point(int a,int b,int c){//this(a,b); x=a;y=b; z=c;}}thisPoint(int a,int b,int c){ this(a,b); //must be at the first line z=c;}
-
//=new ([])//
=new([])
-
Class Declaration ()Example:
class Body {public long idNum;public String name;public Body orbits;
public static long nextID = 0;}
-
Creating ObjectsEg.: Body earth;earth = new Body();
create an object by invoking a constructor and its arguments if there is any;the runtime system allocates enough space to store the fields of the object;initialize the objects variables;
-
//Point.javaclass Point{int x,y;
Point(int a,int b){ // x=a; y=b;}}//A.javapublic class A{public static void main(String args[]){Point p1, p2, p3;p1=new Point(10,10);p2=new Point(5,6);p3=p1;}}
-
()1)Point p1;2)p1 = new Point(10, 10);x, yp1p1p1null0xAB12
-
3)p1=new Point(10, 10);p2=new Point(5, 6);
-
Methods()A method consists of two parts: the method header ;the method body;
The method header consists of a set of modifiers, the method return type, signature and a throws clause for exceptions;The method signature consists of the method name and the parameter type list enclosed in ( ); The method body consists of statements enclosed between { and }. () { /*method body*/ }
-
Example:
class Body {public long idNum;public String name;public Body orbits;public static long nextID = 0;
Body(String s){this.Name = s;}}
-
Methods ()class BodyPrint{ public static void main(String[] args) { Body sun=new Body(Sun); Body earth=new Body(Earth); earth.orbits=sun; System.out.println(Body +earth.name+ orbits +earth.orbits.name) }}
-
Methods ()Methods can have a return type, either a primitive type or a reference type;If a method does not return any value, the place where a return type would go is filled with a void.
-
Method Modifiers()access modifiers: same as modifiers of variables;abstractstaticfinalsynchronizednativestrictfp: strict floating point
An abstract method cannot be static, final, synchronized, native, or strict.
-
Static Methods/Class Methods/A static method is invoked on behalf of an entire class, not on a specific object.A static method might perform a general task for all objects of the class;
A static method can access only static fields and other static methods of the class;
-
()(not recommended)
-
()class A {int a;static int b;
void f(int x,int y) {a=x;b=y;}
static void g(int z){///b=23;a=z; //legal or not?}}//
-
Method Invocation()How to invoke a method:
reference. method(arguments)
When a method is invoked, the caller must provide an argument of the appropriate type for each of the parameters declared by the method.
-
Method Execution() & ReturnWhen a method is invoked, the statements of the method are executed;A method completes execution and returns to the caller when:a return statement is executed;the end of the method;an uncaught exception is thrown.
A method can only return a single result if a method returns any result.
-
Overload()int add(int i,int j){ return i+j; }
float add(float i,float j){ return i+j; }
int add(int i,int j,int k){ return i+j+k; }
-
Parameter() ValuesParameter Passing()Pass by value()For all premitive types, values of parameter variables in a method copies of the values of arguments passed.Pass object reference by value()When the parameter is an object reference, the object reference() is passed by value;the object referred to by the reference can be changed.
-
//Pass by value()class PassByValue{ public static void main(String[] args){ double one=1.0; System.out.println(before: one=+one); halveIt(one); System.out.println(after: one=+one); }
public static void halveIt(double arg){ arg=arg/2.0; System.out.println(havled: arg=+arg); }}before one=1.0halved arg=0.5after: one=1.0
-
Example:
class Body {public long idNum;public String name;public Body orbits;public static long nextID = 0;
Body(String s){this.name = s;}}
-
//Pass object reference by value()class PassRef{
public static void main(String[] args){ Body sirius=new Body("Sirius"); // System.out.println("before: "+sirius.name); commonName(sirius); System.out.println("after: "+sirius.name); }
public static void commonName(Body bodyRef){ bodyRef.name="Dog Star";// bodyRef=null; }}before: Siriusafter: Dog Star
-
AssignmentsComplete exercises as follows:P51 Exercise 2.9 P54 Exercise 2.10 P59 Exercise 2.12P59 Exercise 2.14 P61 Exercise 2.16 P62 Exercise 2.17
class Xiyoujirenwu{float height,weight;String head,ear,hand,foot,mouth;void speak(String s){head="";System.out.println(s);}}class E_monkey{public static void main(String args[]){Xiyoujirenwu zhubajie,sunwukong;zhubajie=new Xiyoujirenwu();sunwukong=new Xiyoujirenwu();zhubajie.height=1.80f;zhubajie.weight=160f;zhubajie.hand="";zhubajie.foot="";zhubajie.head="";zhubajie.ear="";zhubajie.mouth="";sunwukong.height=1.62f;sunwukong.weight=1000f;sunwukong.hand="";sunwukong.foot="";sunwukong.head="";sunwukong.ear="";sunwukong.mouth="";System.out.println("zhubajie"+zhubajie.height);System.out.println("zhubajie"+zhubajie.head);System.out.println("sunwukong"+sunwukong.weight);System.out.println("sunwukong"+sunwukong.head);zhubajie.speak("");System.out.println("zhubajie"+zhubajie.head);sunwukong.speak("1000");System.out.println("sunwukong"+sunwukong.head);}}