Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP201 Java Programming Topic 3: Classes and Objects Readings: Chapter 4.

Similar presentations


Presentation on theme: "COMP201 Java Programming Topic 3: Classes and Objects Readings: Chapter 4."— Presentation transcript:

1 COMP201 Java Programming Topic 3: Classes and Objects Readings: Chapter 4

2 COMP201 Topic 3 / Slide 2 Objective l Objective: Shows how to write and use classes

3 COMP201 Topic 3 / Slide 3 Using Predefined Classes Date Class Date : its objects describe points in time, such as 7/2/2005, 13:00:00. GMT To construct a Date Object: new Date (); l You can also pass the object to a method: n System.out.println(new Date()); n String s = new Date().toString(); Or store it to a variable: Date birthday = new Date(); l Objects and object variables are different. Date deadline ; // deadline is not an object and doesn’t refer to an object yet. if you set: deadline = birthday; n // both variables refer to the same object.

4 COMP201 Topic 3 / Slide 4 Using Predefined Classes GregorianCalendar GregorianCalendar : expresses dates in the familiar calendar notation. Constructors: new GregorianCalendar(); //Create a object that represents the date and time at which the object was constructed. new GregorianCalendar(2005,1,14); //construct a object for the //midnight on a specified date OR new GregorianCalendar(2005,Calendar.February, 7 13,59,59); l Mutator and Accessor Methods: GregorianCalendar now = new GregorianCalendar(); int month = now.get(Calendar.Month); int weekday = now.get(Calendar.DAY_OF_WEEK); now.set(Calendar.YEAR, 2006); now.set(Calendar.MONTH, Calendar.APRIL); now.set(Calendar.DAY_OF_MONTH, 1); now.add(Calendar.MONTH,3); //move now by 3 months

5 COMP201 Topic 3 / Slide 5 Convertion between Date and GregorianCalendar If you know the year, month, and day, and you want to make a Date object with those setting. Because the Date class knows nothing about calendars, first construct a GregorianCalendar object and then call the getTime to obtain a Date : GregorianCalendar Holiday = new GregorianCalendar(year, month,day); Date highTime = Holiday.getTime(); You can also set a GregorianCalendar from a Date Holiday.setTime(highTime); // to set Calendar

6 COMP201 Topic 3 / Slide 6 Using Predefined Classes An Example l We capture the current day and month by calling the get method: GregorianCalendar d = new GregorianCalendar(); int today = d.get(Calendar.DAY_OF_WEEK); int month = d.get(Calendar.MONTH); Set d to the first of the month and get the weekday of that date d.set(Calendar.DAY_OF_MONTH,1); int weekday = d.get(Calendar.DAY_OF_WEEK); Advance d to the next day: d.add(Calendar.DAY_OF_MONTH,1); //CalendarTest.java

7 COMP201 Topic 3 / Slide 7 Ingredients of a Class l A class is a template or blueprint from which objects are created. class NameOfClass { constructor1// construction of object constructor2 。。。 method1// behavior of object method2 。。。 field1// state of object field2 。。。 } // See EmployeeTest.java

8 COMP201 Topic 3 / Slide 8 Outline l Ingredients of a class n Instance fields n Initialization and constructors n Methods n Class modifiers l Packages: How classes fit together

9 COMP201 Topic 3 / Slide 9 Instance Fields class Employee {... private String name; private double salary; private Date hireDay; //java.util.Datejava.util.Date } l Various types of fields n Classification according to data type –A field can be of any primitive type or an object of any class n Classification according to accessibility –public, default, protected, private n Classification according to host –static vs non-static

10 COMP201 Topic 3 / Slide 10 Instance Fields l Access modifiers: private : visible only within this class class Employee {... public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } private double salary; } Default (no modifier): visible in package protected : visible in package and subclasses

11 COMP201 Topic 3 / Slide 11 n public: visible everywhere n 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. class Employee {... public double getSalary() // accessor method { return salary; } // mutator method public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } private double salary; // private field } Instance Fields

12 COMP201 Topic 3 / Slide 12 static Instance Fields n Static fields belong to class, not object class Employee //StaticTest.java {... public void setId() { id = nextID; nextID++; } private int id; private static int nextID =1; } n Usage: className.staticField NOT objectName.staticField although the later works also. –Employee.nextID, harry.NextID, jack.NextID

13 COMP201 Topic 3 / Slide 13 l What if the static in front of nextID is removed? class Employee {... public void setId() { id = nextID; nextID++;} private int id; private int nextID = 1; } Employee[] staff = new Employee[3]; staff[0] = new Employee("Tom", 40000); staff[1] = new Employee("Dick", 60000); staff[2] = new Employee("Harry", 65000); for (Employee e : staff) {e.setId();} //They all get have id 1. static Instance Fields

14 COMP201 Topic 3 / Slide 14 final Instance Fields l Constants: Declared with static final. n Initialized at declaration and cannot be modified. l Example: Public class Math { … public static final double PI = 3.141592; … } //Called with Math.PI l Notes: n Static fields are rare, static constants are more common. n Although we should avoid public fields as a principle, public constants are ok. –Examples: System.out, System.in

15 COMP201 Topic 3 / Slide 15 Outline l Ingredients of a class n Instance fields n Initialization and constructors n Methods n Class modifiers l Packages: How classes fit together

16 COMP201 Topic 3 / Slide 16 Initialization of Instance Fields l Several ways: 1. Explicit initialization 2. Initialization block 3. Constructors

17 COMP201 Topic 3 / Slide 17 l Explicit initialization: initialization at declaration. private double salary = 0.0; private String name = “”; l Initialization value does not have to be a constant value. class Employee { … static int assignId() { int r = nextId; nextId++; return r; }… private int id = assignId(); private static int nextId=1; } Initialization of Instance Fields

18 COMP201 Topic 3 / Slide 18 l Initialization block: n Class declaration can contain arbitrary blocks of codes. class Employee { … // object initialization block { id = nextId; nextId++; } … private int id; private static int nextId=1; } Initialization of Instance Fields

19 COMP201 Topic 3 / Slide 19 l Initialization by constructors class Employee { public Employee(String n, double s, int year, int month, int day) {name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day) // GregorianCalendar uses 0 for January hireDay = calendar.getTime(); } private String name; private double salary; private Date hireDay; } Initialization of Instance Fields

20 COMP201 Topic 3 / Slide 20 l What happens when a constructor is called All data fields initialized to their default value ( 0, false, null ) n Field initializers and initialization blocks are executed n Body of the constructor is executed –Note that a constructor might call another constructor at line 1. Initialization of Instance Fields

21 COMP201 Topic 3 / Slide 21 l Default constructor: n Constructor with no parameters class Employee {... public Employee() { name =“”; salary = 0; } } Initialization of Instance Fields

22 COMP201 Topic 3 / Slide 22 l If a programmer provides no constructors, Java provides a default constructor that set all fields to default values –Numeric fields, 0 –Boolean fields, false –Object variables, null l 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 have only the constructor shown on slide 19, then New Employee(); // not ok Initialization of Instance Fields

23 COMP201 Topic 3 / Slide 23 Constructors l Constructors define initial state of objects class Employee {public Employee( String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); // GregorianCalendar uses 0 for January hireDay = calendar.getTime(); } private String name; private double salary; private Date hireDay; } Employee hacker = new Employee("Harry Hacker",35000, 1989,10,1);

24 COMP201 Topic 3 / Slide 24 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 –Almost always public, although can be others –Always called with the new operator Constructors

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

26 COMP201 Topic 3 / Slide 26 Calling another constructor l Can call another constructor at line 1: class Employee { public Employee(String name, double salary){...} public Employee(double salary) { this(“Employee #” + nextID, salary ); nextID++; } l Write common construction code only once

27 COMP201 Topic 3 / Slide 27 Object Creation l Must use new to create an object instance Employee hacker = new Employee("Harry Hacker", 35000, 1989,10,1); This is illegal: Employee number007(“Bond”, 1000, 2002, 2, 7);

28 COMP201 Topic 3 / Slide 28 l No delete operator. Objects are destroyed automatically by garbage collector l Periodically garbage collector destroy objects not referenced. To force garbage collection, call System.gc(); l To timely reclaim non-memory resources (IO connection), add a finalize method to your class. n 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. Object Destruction

29 COMP201 Topic 3 / Slide 29 Outline l Ingredients of a class n Instance fields n Initialization and constructors n Methods n Class modifiers l Packages: How classes fit together

30 COMP201 Topic 3 / Slide 30 Methods l Three key characteristics of objects n Identity n State –Values of fields n Behavior –What can we do with them? l Methods determine behavior of objects

31 COMP201 Topic 3 / Slide 31 class Employee { public String getName() {...} public double getSalary() {...} public Date getHireDay() {...} public void raiseSalary(double byPercent) {...} } Methods

32 COMP201 Topic 3 / Slide 32 Methods l Plan: n Types of methods n Parameters of methods (pass by value) n Function overloading

33 COMP201 Topic 3 / Slide 33 Methods l Types of methods n Classification according to functionality –Accessor, mutator, factory n Classification according to accessibility –public, protected, default, private n Classification according to the host –static vs non-static

34 COMP201 Topic 3 / Slide 34 Types of Methods n Accessor methods: public String getName() { return name; } n Mutator methods: Public void setSalary(double newSalary) { salary = newSalary; }

35 COMP201 Topic 3 / Slide 35 Types of Methods Factory methods. The NumberFormat class uses factory methods that yield formatter objects for various styles. n Produce objects NumberFormat.getNumberInstance() // for numbers NumberFormat.getCurrencyInstance()//currency values NumberFormat.getPercentInstance()//percentage value l Why useful? (We already have constructors) n More flexibility in name –Constructors must have the same name as class. But sometimes other names make sense. n Factory methods can generate object of subclass, but constructors cannot.

36 COMP201 Topic 3 / Slide 36 Simple Input/Output l For Example: double x = 10000.0 / 3.0; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(4); nf.setMinimumIntegerDigits(6); System.out.println(nf.format(x));//003,333.3333

37 COMP201 Topic 3 / Slide 37 Accessibility of Methods public : visible everywhere protected : visible in package and in subclasses Default (no modifier): visible in package private : visible only inside class (more on this later) l A method can access fields and methods that are visible to it. n public method and fields of any class n protected fields and methods of superclasses and classes in the same package n Fields and methods without modifiers (default) of classes in the same packages n private fields and methods of the same class.

38 COMP201 Topic 3 / Slide 38 Accessibility of Methods A method can access the private fields of all objects of its class class Employee {... public boolean equals(Employee another) { retun name.equals(another.name); } private String name; }

39 COMP201 Topic 3 / Slide 39 Public method and private field Bad idea for a public method to return a private object class Employee { public Date getHireDay() { return hireDay;} private String name; private double salary; private Date hireDay; } Other classes can get the object and modify, although it is supposed to be private to Employee. Better solution: public Date getHireDay() { return hireDay.clone();}

40 COMP201 Topic 3 / Slide 40 Static Methods Declared with modifier static. l It belongs to class rather than any individual object. Sometimes called class method. Usage: className.staticMethod() NOT objectName.staticMethod() class Employee {public static int getNumOfEmployees() { return numOfEmpolyees; } private static int numOfEmployees = 0; … } Employee.getNumOfEmployee(); // ok Harry.getNumOfEmployee(); // not this one

41 COMP201 Topic 3 / Slide 41 Static methods l Explicit and implicit parameters: class Employee { public void raiseSalary(double byPercent) {...} } Explicit parameters: byPercent Implicit parameters: this object l Static methods do not have the implicit parameter public class Math{ public static double pow(double x, double y) {...} } Math.pow(2, 3);

42 COMP201 Topic 3 / Slide 42 Static Methods l The main method class EmployeeTest {public static void main(String[] args) { } } is always static because when it is called, there is no objects yet.

43 COMP201 Topic 3 / Slide 43 Static Methods l A static method cannot access non-static fields class Employee { public static int getNumOfEmployees() { return id; // does not compile // id == this.id } private static int numOfEmployees = 0; private int id = 0; }

44 COMP201 Topic 3 / Slide 44 Parameters of Method l Parameter (argument) syntax same as in C n Parameters are all passed by value, not by reference n Value of parameter copied in function call public static void doubleValue( double x) { x = 2 * x; } double A = 1.0; doubleValue( A ); // A is still 1.0 1.0 2.0 A= x=

45 COMP201 Topic 3 / Slide 45 Parameters of Method l When parameters are object references l Parameter values, i.e. object references are copied public void swap( Employee x, Employee y) { Employee tmp = x; x=y; y=tmp; } Employee A = new Employee(“Alice”,.. Employee B = new Employee(“Bob”,.. Swap(A, B) B= x= Alice y= Bob A=

46 COMP201 Topic 3 / Slide 46 // a function that modify content of object, // but not object reference void bonus(Employee A, double x) { A.raiseSalary(x);//a.salary modified although a is not } //ParamTest.java Parameters of Method salary A=

47 COMP201 Topic 3 / Slide 47 Command-Line arguments Parameters of the main Method 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 //CommandLine.java

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

49 COMP201 Topic 3 / Slide 49 Resolution of Overloading l Compiler finds best match n Prefers exact type match over all others n Finds “closest” approximation n Only considers widening conversions, not narrowing l 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)

50 COMP201 Topic 3 / Slide 50 Outline l Ingredients of a class n Instance fields n Initialization and constructors n Methods n Class modifiers l Packages: How classes fit together

51 COMP201 Topic 3 / Slide 51 Class Modifiers public : visible everywhere public class EmployeeTest {... } l Default (no modifier): visible in package class Employee {... } private : only for inner classes, visible in the outer class (more on this later) public class Tree {... private class TreeNode{...} }

52 COMP201 Topic 3 / Slide 52 Outline l Ingredients of a class n Instance fields n Initialization and constructors n Methods n Class modifiers l Packages: How classes fit together

53 COMP201 Topic 3 / Slide 53 Packages l Plan n What are packages n Creating packages n Using packages

54 COMP201 Topic 3 / Slide 54 Packages l A package consists of a collection of classes and interfaces l Information about packages in JSDK 1.5.0 can be found http://java.sun.com/j2se/1.5.0/docs/api/index.html l Example: n Package java.lang consists of the following classes n Boolean Byte Character Class ClassLoader Compiler Double Float Integer Long Math Number Object SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread … BooleanByteCharacterClassClassLoaderCompiler DoubleFloatIntegerLongMathNumberObject SecurityManagerShortStackTraceElement StrictMathStringStringBufferSystemThread

55 COMP201 Topic 3 / Slide 55 Packages l Packages are convenient for organizing your work l Guarantee uniqueness of class names n Complete name of class: package name + class name n Avoids name conflict. Example –java.sql.Date –java.util.Date l Packages are organized hierarchically, just like nested subdirectory on your computer. n Example –java.securityjava.security –java.security.acl java.security.cert java.security.interfaces java.security.specjava.security.acljava.security.certjava.security.interfaces java.security.spec n For java compiler, however, java.security and java.security.acl are just two packages, having nothing to do with each other.java.securityjava.security.acl

56 COMP201 Topic 3 / Slide 56 Creating Packages To add to class to a package, say foo n Begin the class with the line package foo; This way we can add as many classes to foo as we wish Where should we keep the class in the foo package? In a directory name foo : –.../ foo /{first.class, second.class,...} l Sub packages and subdirectories must match All classes of foo.bar must be placed under... / foo / bar / All classes of foo. bar.util must be under.../ foo / bar / util /

57 COMP201 Topic 3 / Slide 57 Creating Packages Classes that do not begin with “package... ” belongs to the default package: n The package located at the current directory, which has no name n Consider a class under.../foo/bar/ –If it starts with “ package foo.bar ”, it belongs to the package “ foo.bar ” –Else it belong to the default package

58 COMP201 Topic 3 / Slide 58 Using Packages Use full name for a class: packageName.className java.util.Date today = new java.util.Date(); Use import so as to use shorthand reference. It is merely a convenience differ from “include” directive in C++. import java.util.*; Date today = new Date(); Can import all classes in a package with wildcard n import java.util.*; 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

59 COMP201 Topic 3 / Slide 59 Using packages l Resolving Name Conflict 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? n Solution: import java.util.*; import java.sql.*; import java.util.Date; n What if we need both? Use full name java.util.Date today = new java.util.Date(); java.sql.Date deadline = new java.sql.Date();

60 COMP201 Topic 3 / Slide 60 Static Imports The import statement can even import static methods and fields, not just classes. For example, if you add: Import static java.lang.System.*; Then you can output by out.println(“Good bye cruel world”); l More useful, you can use a static import for the Math class, and use mathematical functions in a more natural way. For example, sqrt(pow(x,2) + pow(y,2));

61 COMP201 Topic 3 / Slide 61 Using packages n Informing java compiler and JVM location of packages n Set the class path environment variable: –On UNIX/Linux: Add a line such as the following to.cshrc setenv CLASSPATH /home/user/classDir1:/home/user/classDir2:. –The separator “:” allows you to indicate several base directories where packages are located. –Java compiler and JVM will search for packages under both of the following two directories /home/user/classDir1/ /home/user/classDir2/ –The last “.” means the current directory. Must be there.

62 COMP201 Topic 3 / Slide 62 Using Packages Set the CLASSPATH environment variable: –On Windows 95/98: Add a line such as the following to the autoexec.bat file SET CLASSPATH=c:\user\classDir1;\user\classDir2;. l Now, the separator is “;”. –On Windows NT/2000/XP: Do the above from control panel

63 COMP201 Topic 3 / Slide 63 l Example: setenv CLASSPATH /homes/lzhang/DOS/teach/201/code/:/appl/Web /HomePages/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. Using Packages


Download ppt "COMP201 Java Programming Topic 3: Classes and Objects Readings: Chapter 4."

Similar presentations


Ads by Google