COMP 201 Java Programming Topic 3 Classes and















































- Slides: 47

COMP 201 Java Programming Topic 3: Classes and Objects Readings: Chapter 4 Especially “documentation and class design hints” 1

COMP 201 Topic 3 / Slide 2 Outline l An Example: What does a Java class look like l Ingredients of a class: How to write a class Instance fields n Initialization and constructors n Methods n Class modifiers n l Packages: How classes fit together 2

COMP 201 Topic 3 / Slide 3 An Example class Employee { // constructor public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; Gregorian. Calendar calendar = new Gregorian. Calendar(year, month - 1, day); // Gregorian. Calendar uses 0 for January hire. Day = calendar. get. Time(); } // methods public String get. Name() { return name; } 3

COMP 201 Topic 3 / Slide 4 An Example public double get. Salary() { return salary; } public Date get. Hire. Day() { return hire. Day; } public void raise. Salary(double by. Percent) { double raise = salary * by. Percent / 100; salary += raise; } private String name; private double salary; private Date hire. Day; } 4

COMP 201 Topic 3 / Slide 5 An Example import java. util. *; public class Employee. Test { public static void main(String[] args) { // fill the staff array with three Employee objects Employee[] staff = new Employee[3]; staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15); staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); 5

COMP 201 Topic 3 / Slide 6 An Example // raise everyone's salary by 5% for (int i = 0; i < staff. length; i++) staff[i]. raise. Salary(5); // print out information about all Employee objects for (int i = 0; i < staff. length; i++) { Employee e = staff[i]; System. out. println("name=" + e. get. Name() + ", salary=" + e. get. Salary() + ", hire. Day=" + e. get. Hire. Day()); } } } //Employee. Test. java 6

COMP 201 Topic 3 / Slide 7 Date and Gregorian. Calendar l Date: a class belong to the standard Java library. An instance of the Date class has a state, means a particular point in time, represented by the number of milliseconds from a fixed point. l Gregorian. Calendar: expresses dates in the familiar calendar notation. new Gregorian. Calendar() //date & time when constructed //midnight of Chinese New Year eve Gregorian. Calendar now=new Gregorian. Calendar(2002, 2, 11) int month = now. get(Calendar. MONTH); int day = now. get(Calendar. DAY_OF_WEEK); l Converting between Date and Gregorian. Calendar Date time = now. get. Time(); now. set. Time(time); 7

COMP 201 Topic 3 / Slide 8 Output of the Example name=Carl Cracker, salary=78750. 0, hire. Day=Tue Dec 15 00: 00 GMT+08: 00 1987 name=Harry Hacker, salary=52500. 0, hire. Day=Sun Oct 01 00: 00 GMT+08: 00 1989 name=Tony Tester, salary=42000. 0, hire. Day=Thu Mar 15 00: 00 GMT+08: 00 1990 8

COMP 201 Topic 3 / Slide 9 Ingredients of a Class l A class is a template or blueprint from which objects are created. class Name. Of. Class { constructor 1 // construction of object constructor 2 … method 1 // behavior of object method 2 … field 1 // state of object field 2 … } 9

COMP 201 Topic 3 / Slide 10 Instance Fields l Instance fields describe state of object l Plan: n Various types of instance fields n Initialization of instance fields 10

COMP 201 Topic 3 / Slide 11 Instance Fields l Access modifiers: n private: visible only within this class Default (no modifier): visible in package n protected: visible in package and subclasses n public: visible everywhere n l It is never a good idea to have public instance fields because everyone can modify it. Normally, we want to make fields private. OOP principle. 11

COMP 201 Topic 3 / Slide 12 Final Instance Fields n Declared with modifier final. Must be initialized when object is created. n Cannot be modified afterwards, n Example: class Employee { … private final String name; } n 12

COMP 201 Topic 3 / Slide 13 Static Instance Fields n Declared with modifier static. n It belongs to class rather than any individual object. n Usage: class. Name. static. Field object. Name. static. Field n NOT Examples: System. out, System. in 13

COMP 201 Topic 3 / Slide 14 Static Instance Field class Employee {public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; Gregorian. Calendar calendar = new Gregorian. Calendar(year, month - 1, day); hire. Day = calendar. get. Time() num. Of. Empoyees ++; } … public static int num. Of. Employees = 0; …} Employee. num. Of. Empoyees; // ok Employee hacker = new Employee(…); hacker. num. Of. Employee; // wrong 14

COMP 201 Topic 3 / Slide 15 Static Final Instance Fields l l Constants: n Declared with static final. n Initialized at declaration and cannot be modified. Example: Public class Math { … public static final double PI = 3. 141592; … } l Notes: Static fields are rare, static constants are more common. n Although we should avoid public fields as a principle, public constants are ok. n 15

COMP 201 Topic 3 / Slide 16 Initialization of Instance Fields l Several ways: n Explicit initialization n Initialization block n Default initialization n Constructors 16

COMP 201 Topic 3 / Slide 17 Initialization of Instance Fields l Explicit initialization: initialization at declaration. public static int num. Of. Employees = 0; public static final double PI = 3. 141592; l Initialization value does not have to be a constant value. class Employee { … static int assign. Id() { int r = next. Id; next. Id++; return r; }… private int id = assign. Id(); private static int next. Id=1; } 17

COMP 201 Topic 3 / Slide 18 Initialization of Instance Fields l Initialization block: n Class declaration can contain arbitrary blocks of codes. n Those blocks are executed when object are being constructed. class Employee { … // object initialization block { id = next. Id; next. Id++; } … private int id; private static int next. Id=1; } 18

COMP 201 Topic 3 / Slide 19 Initialization of Instance Fields class Employee {public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; Gregorian. Calendar calendar = new Gregorian. Calendar(year, month - 1, day); // Gregorian. Calendar uses 0 for January hire. Day = calendar. get. Time(); } new Employee("Harry Hacker", private String name; private double salary; 35000, 1989, 10, 1); private Date hire. Day; 19 }

COMP 201 Topic 3 / Slide 20 Default Initialization If programmer provides no constructors, Java provides an a default constructor that set all fields to default values – Numeric fields, 0 – Boolean fields, false – Object variables, null Note: If a programmer supplies at least one constructor but does not supply a default constructor, it is illegal to call the default constructor. In our example, the following should be wrong if we don’t have the constructor shown on the previous slide: New Employee(); // not ok 20

COMP 201 Topic 3 / Slide 21 Initialization l l l Java initializes instance fields to a default (0, null for objects, false) if you don’t initialize them explicitly using a constructor. If there is no constructor, a default constructor is invoked to do the initialization. Unlike in C++, you can initialize instance fields directly in the class definition. class Customer{ ……… private int next. Order =1; } 21

COMP 201 Topic 3 / Slide 22 Constructors n. A class can have one or more constructors. n A constructor – Has the same name as the class – May take zero, one, or more parameters – Has no return value – Always called with the new operator 22

COMP 201 Topic 3 / Slide 23 Default Constructors with no parameters. n Written by programmer or supplied automatically by Java. n public Employee() { name = “”; salary = 0; hire. Day = null; } 23

COMP 201 Topic 3 / Slide 24 Order of initialization l l Default values assigned or properties set to default value If the first line of the constructor calls another constructor then that constructor is executed. All field initializers and initialization blocks are executed, in the order they occur in the class declaration. The body of the constructor is executed. 24

COMP 201 Topic 3 / Slide 25 Using this in Constructors this refers to the current object. n More meaningful parameter names for constructors public Employee(String name, double salary, int year, int month, int day) { this. name = name; n this. salary = salary; 本 … } l No copy constructor in Java. To copy objects, use the clone method, which will be discussed later. 25

COMP 201 Topic 3 / Slide 26 Object Creation and Destruction l Must use new to create an object instance Employee hacker = new Employee("Harry Hacker", 35000, 1989, 10, 1); This is illegal: Employee number 007(“Bond”, 1000, 2002, 2, 7); l No delete operator. Objects are destroyed automatically by garbage collector l To timely reclaim resources, add a finalize method to your class. This method is called usually before garbage collect sweep away your object. But you never know when. l A better way is to add a dispose method to your class and call it manually in your code. 26

COMP 201 Topic 3 / Slide 27 Methods l Methods are functions that determine what we can do to objects Parameter (argument) syntax same as in C Parameters are all passed by value; But note that identifiers to objects (array, strings, etc. ) are actually references. While the references cannot be modified, contents of objects might. Return value can be anything, including an array or an object. l Plan: l l Types of methods n Parameters of methods n Function overloading n Access rights of methods n 27

COMP 201 Topic 3 / Slide 28 Type of Methods n Accessor methods: public String get. Name() { return name; } n Mutator methods: Public void set. Salary(double new. Salary) { salary = new. Salary; } n Factory methods: generate objects of the same class. Will discuss later. 28

COMP 201 Topic 3 / Slide 29 Static Methods n Declared with modifier static. It belongs to class rather than any individual object. n Usage: class. Name. static. Method() NOT n object. Name. static. Method() n Examples: – public static void main(String args[]) Because we don’t have any objects at the beginning. 29

COMP 201 Topic 3 / Slide 30 Methods class Employee {public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; Gregorian. Calendar calendar = new Gregorian. Calendar(year, month - 1, day); hire. Day = calendar. get. Time(); num. Created++; } … public static int get. Num. Of. Employees() { return num. Of. Empolyees; } private static int num. Of. Employees = 0; …} Employee. get. Num. Of. Employee(); // ok Harry. get. Num. Of. Employee(); // not ok 30

COMP 201 Topic 3 / Slide 31 A Diversion/Command-Line arguments public static void main(String args[]) { for (int i=0; i<args. length; i++) System. out. print(args[i]+“ ”); System. out. print(“n”); } // note that the first element args[0] is not // the name of the class, but the first // argument //Command. Line. java 31

COMP 201 Topic 3 / Slide 32 Parameters l Parameter (argument) syntax same as in C n Parameters are all passed by value; – A method cannot modify the values of parameter variables. n But note that values of object variables are actually references (locations) of objects. While the references cannot be modified, states of objects might. 32

COMP 201 Topic 3 / Slide 33 Parameters/Pass by Value Employee a = new Employee(“Alice”, …. ); Employee b = new Employee(“Bob”, …. ); swap(a, b); …. // a swap function with no effect void swap(Object x, Object y) { Object temp = x; x = y; y = temp; } //The x and y parameters of the swap method are initialized with copies of a, b. After swap, x refers to Bob and y to Alice, but the original variables a and b still refer to the same objects as they did before the method call. ( Param. Test. java) 33

COMP 201 Topic 3 / Slide 34 Parameters/Pass by Value // a function that modify objects void bonus(Employee a, double x) { a. raise. Salary(x); //a. salary modified although a is not } //Param. Test. java 34

COMP 201 Topic 3 / Slide 35 Function Overloading n Can re-use names for functions with different parameter types void sort (int[] array); void sort (double[] array); n Can have different numbers of arguments void indexof (char ch); void indexof (String s, int start. Position); n Cannot overload solely on return type void sort (int[] array); boolean sort (int[] array); // not ok 35

COMP 201 Topic 3 / Slide 36 Resolution of Overloading n Compiler finds best match – Prefers exact type match over all others – Finds “closest” approximation – Only considers widening conversions, not narrowing n Process is called “resolution” void binky (int i, int j); void binky (double d, double e); binky(10, 8) //will use (int, int) binky(3. 5, 4) //will use (double, double) 36

COMP 201 Topic 3 / Slide 37 Access rights of methods l l A method can access the public fields and methods of any classes that are visible to it (see next slide). A method of a class can access the private fields of any objects of the same class: class Employee { … Boolean equals(Employee other) { return name. equal( other. name ); } } In if (harry. equals( boss) …) method equals accesses the private field name of both harry and boss. 37

COMP 201 Topic 3 / Slide 38 Class Modifiers l l Default (no modifier): visible in package public: visible everywhere private: only for inner classes, visible in the outer class (more on this later) Each source file can contain at most one public class, which must have the same name as the file. File: Employee. Test. java public class Employee. Test {…} class Employee {…} 38

COMP 201 Topic 3 / Slide 39 Packages l Classes are grouped into packages. l A program involves multiple packages. l Next: Finding information about existing packages n Creating your own package n Using packages (to build a program) n Informing Java compiler where packages are located. n 39

COMP 201 Topic 3 / Slide 40 Information About Existing Packages l Information about existing packages can be found online http: //java. sun. com/products/jdk/1. 3/docs/api/ Linked to course page. l Examples: java. lang, java, lang. reflect n Java. util, java. util. jar, java. util. zip n n Packages are organized hierarchically. 40

COMP 201 Topic 3 / Slide 41 Creating Your Own Package l To create a package named foo, Create a directory with that name: class. Dir/foo n Add line “package foo; ” to the top of all class files of the package n Place the class files under foo or its subdirectories. n l To create a sub-package of foo named bar, Create a subdirectory named bar: class. Dir/foo/bar n Add line “package bar; ” to the top of all class files of the package n Place the class files under bar or its subdirectories. n The sub-package is known as “foo. bar”. n 41

COMP 201 Topic 3 / Slide 42 Creating Your Own Packages n If a class file has no package specification, it belongs to the default package located at the current directory. n If a class file under base. Dire/foo/bar does not contain the “package …” line, it belongs to foo. bar by default. n If you want it to be part of foo, you must add line “package foo; ” to the top. //Package. Test. java 42

COMP 201 Topic 3 / Slide 43 import Packages l Full name for a class: package. Name. class. Name Java. util. Date today = new Java. util. Date(); l Use import so as to to use shorthand reference import java. util. *; Differ from “include” directive in Date today = new Date(); C++. Merely a convenience. l Can import all classes in a package with wildcard n import java. util. *; n Makes everything in the java. util package accessible by shorthand name: Date, Hashtable, etc. o Everything in java. lang already available by short name, no import necessary 43

COMP 201 Topic 3 / Slide 44 Resolving Name Conflict l Both java. util and java. sql contain a Date class import java. util. *; import java. sql. *; Date today; //ERROR--java. util. Date or java. sql. Date? l Solution: import java. util. *; import java. sql. *; import java. util. Date; l What if we need both? Use full name java. util. Date today = new java. util. Date(); java. sql. Date deadline = new java. sql. Date(); 44

COMP 201 Topic 3 / Slide 45 Using Packages l Java compiler has “make” facility built-in, n It automatically searches for classes used – Runtime library files (under jre/lib and jre/lib/ext) – In files under current directory – In imported packages. l No makefile necessary 45

COMP 201 Topic 3 / Slide 46 Informing Compiler Locations of Packages l l Can do from command line, but inconvenient Set the CLASSPATH environment variable: n On UNIX/Linux: Add a line such as the following to. cshrc setenv CLASSPATH /home/user/class. Dir 1: /home/user/class. Dir 2: . – The separator “: ” allows you to indicate several base directories where packages are located. – The last “. ” means the current directory. Must be there. n On Windows 95/98: Add a line such as the following to the autoexec. bat file SET CLASSPATH=c: userclass. Dir 1; userclass. Dir 2; . – Now, the separator is “; ”. n On Windows NT/2000: Do the above from control panel 46

COMP 201 Topic 3 / Slide 47 Informing Compiler Locations of Packages l l Example: setenv CLASSPATH /homes/lzhang/DOS/teach/201/code/: /appl/Web /Home. Pages/faculty/lzhang/teach/201/codes/s ervlet/jswdk/lib/servlet. jar: /appl/Web/Home Pages/faculty/lzhang/teach/201/codes/servle t/jswdk/webserver. jar: . jar files: archive files that contain packages. Will discuss later. 47