CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 21
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS Copyright: SPRING 2017 Illinois Institute of Technology/George Koutsogiannakis 1
OOP Review • In previous lecture we discussed: – User defined template classes • Default constructor/ non default constructor(s). • Accessor mutator methods. • to. String method. • Other methods as required by the specification. – Client classes – How to use a static instance variable. – Java packages • Note: You must bring your text to the lectures 2
Java Packages • User defined packaging. – Suppose that we created a package for our user defined template class Auto : package name 1. name 2. name 3; import java. util. Scanner; import java. io. File; public class Auto { ……………… } 3
Java Packages • We compile Command Line using the special command: • >javac –d. Auto. java Notice that there is space between javac and –d and also between –d and the dot. There is also space between the dot and the name of the file. • This command tells the compiler to create the folders first name 1 then name 2 (inside name 1 folder) and then name 3 (inside name 2 folder) with respect to the current directory • and place Auto. class inside folder name 3. 4
Java Packages Current Directory (folder) Source code files Auto. java Auto. Client. java are in Current Directory name 1(folder) name 2 (folder) name 3 (folder) Auto. class 5
Java Packages • • Therefore right now our service class Auto. class file is in folder name 3 in our example. Suppose that we want to use the class Auto in the class Auto. Client and also place Auto. Client in the folder name 2 (not the same folder as the Auto class): – We must import the class Auto in the class Auto. Client by using an import statement in class Auto. Client because the two classes are going to be in different folders i. e. package name 1. name 2 //Notice that Auto. Client resides in folder name 2 import name 1. name 2. name 3. Auto; public class Auto. Client { //now we can instantiate objects of //class Auto and invoke its methods inside //the main method of this class } – File Auto. Client. class will be found in path name 1. name 2 with respect to the current directory. – Note: If both classes reside in the same folder then there is no need to import the Auto class 6
Java Packages Current Directory (folder) Auto. java , Auto. Client. java name 1(folder) name 2 (folder) Auto. Client. class name 3 (folder) Auto. class 7
Java Packages • How do we call the interpreter for class Auto. Client from the current directory (folder)? • We need to list the path to the Auto. Class when we use the interpreter command: i. e >java name 1. name 2. Auto. Client • Notice that the reason we call the Auto. Client class is because this class has the main method. The Auto class will be called automatically. 8
Java Packages • Pre defined library classes are grouped into packages according to their functionality: i. e. package java. lang Provides classes that are fundamental to the design of the Java programming language. Every java program automatically imports all the classes of this package without the need for an import statement. – Includes such classes as : • String, Math , System, Integer, Float and others. 9
Java Packages package java. util – Must explicitly be imported with an import statement. – Provides such classes as: • Scanner, String. Tokenizer, Vector, Calendar, Date and others. java. text – Must imported explicitly. – Provides numeric formatting classes such as: • Format, Number. Format and others 10
Java Packages • Import statements can include the entire package or a selective class out of the package i. e. import java. util. *; imports all classes in package util or import java. util. Scanner; imports only the Scanner class (saves memory usage) 11
Java Packages • There are over 200 packages in the java library – Number of classes varies in each package with some having over 20 classes. – Remember that a package can include something called “interfaces”. – For now let us think of an interface as a class whose methods have no code (no implementation). We will come back to the subject of interfaces later. 12
Default Initial Values If the constructor does not assign values to the instance variables, they receive default values depending on the instance variable data type. Data Type byte, short, int, long float, double Default Value 0 0. 0 char space boolean false Any object reference (for example, a String) null 13
main Method • A client program must contain a method called main() • Execution always begins with the first statement in method main and ends with the last statement in method main. • Between the first and last statement of method main other methods are called for execution as needed. 14
Object Reference this • How does a method know which object's data to use? • this is an implicit parameter sent to methods. this is an object reference to the object for which the method was called. • When a method refers to an instance variable name, this is implied. Thus, variable. Name is understood to be this. variable. Name Example in the Auto class: model. Name is understood to be this. model. Name 15
Using this in a Mutator Method public void set. Instance. Variable( data. Type instance. Variable. Name ) { this. instance. Variable. Name = instance. Variable. Name; } Example: public void set. Model( String model ) { this. model = model; } this. model refers to the instance variable whose value is being set. model refers to the parameter. 16
Using this • Suppose in Auto. Client class (which uses class Auto) we instantiate an object: – Auto a 1=new Auto(); (globally -outside any method) – Suppose that we create a new method that it is responsible for setting the instance fields of a 1 and getting their values by using also a globally declared parameter i. e int x; – We can call the value of x using this. x 17
Using this package folder 1. folder 2; import folder 1. folder 2. folder 3. Auto; public class Auto. Client { Auto a 1=new Auto("Ford", “Mario”, 100, 20); int x=300; public static void main(String[] args) { //because we can NOT directly call a non static method from a static //we need to use an object of Auto. Client ac=new Auto. Client(); ac. using. This(); Auto a 2=new Auto("Infinity", “Jim”, 150, 18); System. out. println(a 2. to. String()); a 2. set. Current. ID(15); System. out. println(“the value of x ia: ”+ac. x); } public void using. This() { a 1. set. Current. ID(15); int x=a 1. get. Current. ID(); System. out. println("The current id for a 1 is now"+" "+this. x); System. out. println("The value of the current id variable for object a 1 is"+" "+x); } } 18
Using this • The output of the previous program is: C: CS 116FALL 2010Practice. ExercisesLecture 2Example. Usingthis>javac -d. Auto. Client. java C: CS 116FALL 2010Practice. ExercisesLecture 2Example. Usingthis>java folder 1. folder 2. Auto. Client The current id for a 1 is now 300 The value of the current id variable for object a 1 is 15 The model is Infinity The owner is Jim The miles driven are 150. 0 The gas mileage is 18. 0 The id is 2 The value of x is: 300 19
Using this • Practice Questions: • What object is the refers this refers to in the Program Auto. Client. java? • Explain the value of all attributes in the output! 20
The equals Method used for objects • Determines if the data encapsulated in another object is equal to the data encapsulated in this object. Return value Method name and argument list boolean equals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise • Example client code using Auto references auto 1 and auto 2: if ( auto 1. equals( auto 2 ) ) System. out. println( "auto 1 equals auto 2" ); 21
The equals Method used for objects • All java objects regardless if the class is user defined or pre defined get to use (the term is “inherit”) methods of a library class called Object. • All classes get to use (the term is “inherit”) the to. String and equals methods of the Object class. • However, quite often we create (as we know) our own to. String method. We can also create our own equals method for objects of our user defined template class. – When we create our version of a method that already exists in the library we call the technique “method overriding”. 22
The instanceof Operator Because the equals method’s parameter is of type Object, we need to determine if the parameter is an Auto object. (Object is general- we need to narrow it down to the specific type of Object). We can use the instanceof operator to determine if an object reference refers to an object of a particular class. Syntax: object. Reference instanceof Class. Name evaluates to true if object. Reference is of Class. Name type; false otherwise. 23
Auto Class equals Method (method overriding of Object class’ equals method). public boolean equals(Object o ) { // if o is not an Auto object, return false if ( ! ( o instanceof Auto ) ) return false; else { // type cast o to an Auto object Auto obj. Auto = ( Auto ) o; if ( this. model. Name. equals( obj. Auto. model. Name ) &&this. miles. Driven== obj. Auto. miles. Driven && Math. abs( this. mileage - obj. Auto. mileage ) < 0. 0001 ) return true; else return false; } } See text Examples 7. 10 Auto. java and 7. 11 Auto. Client. java 24
Auto Class equals Method (method overriding of Object class’ equals method). • When in the Auto. Client class we compare two objects i. e. auto 1 and auto 2 of Auto class as in the statement if (auto 1. equals(auto 2)) this. model. Name in the equals method refers to the value of instance variable model. Name of auto 1 object. The same applies to the other instance variables. 25
Class Scope • Instance variables have class scope – Any constructor or method of a class can directly refer to instance variables. • Methods also have class scope – Any method or constructor of a class can call any other method of a class (without using an object reference). 26
Local Scope • A method's parameters have local scope, meaning that: – a method can directly access its parameters. – a method's parameters cannot be accessed by other methods. • A method can define local variables which also have local scope, meaning that: – a method can access its local variables. – a method's local variables cannot be accessed by other methods. 27
Example of Class vs local scope public class Person { String first. Name; static int I d; int currentid; public Person() { first. Name="John"; id++; currentid=id; } public void method 1() { int currentid; currentid = this. currentid*2; System. out. println("The local value of currentid is"+" "+currentid); System. out. println("The class scope of variable currentid is"+" "+this. currentid); } } currentid defined in method 1() has local scope this. currentid refers to the currentid variable with global class scope as defined at the top of the class and outside any method. 28
Example of Class vs local scope public class Person. Client { public static void main(String[] args) { Person p 1=new Person(); Person p 2=new Person(); p 1. method 1(); p 2. method 1(); } } What is the output ? 29
Example of Class vs Local scope • ----- for object p 1 -----– The local value of currentid is 2 – The class scope of variable currentid is 1 • ----- for object p 2 -----– The local value of currentid is 4 – The class scope of variable currentid is 2 30
enum Types Used to define a set of constant objects. Built into java. lang (no import statement needed) Syntax: enum Enum. Name { obj 1, obj 2, … objn }; Example: enum Days { Sun, Mon, Tue, Wed, Thurs, Fri, Sat }; A constant object is instantiated for each name in the list. Thus, each name is a reference to an object of type Days. enum is a keyword 31
enum Types • Enumerated Types are classes with special properties. • They have a finite number of instances (as for example Days in previous slide). 32
Useful enum Methods Return value Method name and argument list int compare. To( Enum e. Obj ) compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are equal. int ordinal( ) returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on. boolean equals( Object e. Obj ) returns true if this object is equal to the argument e. Obj; returns false otherwise String to. String( ) returns the name of the enum constant 33
Example enum Person. Type { ADULT_MALE, CHILD_MALE, ADULT_FEMALE, CHILD_FEMALE }; public class Persons { Person. Type pt; String first. Name; static int id; int currentid; public Persons() { first. Name="John"; id++; currentid=id; } public void set. Person. Type(Person. Type pertyp) { this. pt=pertyp; } public Person. Type get. Person. Type() { } return pt; } 34
Example enum public class Persons. Client { public static void main(String[] args) { Persons p 1=new Persons(); Persons p 2=new Persons(); p 1. set. Person. Type(Person. Type. ADULT_FEMALE); p 2. set. Person. Type(Person. Type. CHILD_MALE); System. out. println("p 1 is of person type: "+" "+p 1. get. Person. Type()); System. out. println("p 2 is of person type: "+" "+p 2. get. Person. Type()); } } 35
Example enum – ----- Output -----– p 1 is of person type: ADULT_FEMALE – p 2 is of person type: CHILD_MALE 36
Javadocs • Automatic generation of documentation for your user defined classes in html format. • It is another tool available in the jdk (see bin subfolder in the installation folder of the jdk). • To generate documentation use the command javadoc and the nam eof your class followed by the. java extension: – >javadoc Persons. java or – >javadoc *. java (means all files in the folder that end with. java extansion). 37
Javadocs • The tool reads all comments added (/** to */) • plus additional information that we add in the source code file (i. e. describe parameters using the symbol @) i. e. – @ param id denotes the id number of a person advancing for each new Person object instantiated. 38
Javadoc Example /** This class describes Persons */ public class Person { /** @param first. Name provides the first name of a Person */ String first. Name; static int id; int currentid; } public Person() { first. Name="John"; id++; currentid=id; 39
Output html File • • • Package Class Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD Class Person java. lang. Object Person public class Person extends java. lang. Object This class describes Persons Constructor Summary Person() Method Summary void method 1() Methods inherited from class java. lang. Object clone, equals, finalize, get. Class, hash. Code, notify. All, to. String, wait, wait Constructor Detail Person public Person() Method Detail method 1 public void method 1() Package Class Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD 40
- Slides: 40