CS 116 - Illinois Institute of Technology

advertisement
CS 116
OBJECT ORIENTED PROGRAMMING II
LECTURE 2_1
GEORGE KOUTSOGIANNAKIS
Copyright: 2015 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.
• toString 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 name1.name2.name3;
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
name1 then name 2 (inside name1 folder) and then name 3
(inside name 2 folder) with respect to the current directory
• and place Auto.class inside folder name3.
4
Java Packages
Current Directory (folder)
Source code
files
Auto.java
AutoClient.java
are in Current
Directory
name1(folder)
name2 (folder)
name3 (folder)
Auto.class
5
Java Packages
•
•
Therefore right now our service class Auto.class file is in folder name3 in our
example.
Suppose that we want to use the class Auto in the class AutoClient and also place
AutoClient in the folder name2 (not the same folder as the Auto class):
– We must import the class Auto in the class AutoClient by using an import statement in class
AutoClient because the two classes are going to be in different folders i.e.
package name1.name2 //Notice that AutoClient resides in folder name2
import name1.name2.name3.Auto;
public class AutoClient
{
//now we can instantiate objects of
//class Auto and invoke its methods inside
//the main method of this class
}
– File AutoClient.class will be found in path name1.name2 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
,
AutoClient.java
name1(folder)
name2 (folder)
AutoClient.class
name3 (folder)
Auto.class
7
Java Packages
• How do we call the interpreter for class
AutoClient from the current directory (folder)?
• We need to list the path to the AutoClass
when we use the interpreter command:
i.e >java name1.name2.AutoClient
• Notice that the reason we call the AutoClient 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, StringTokenizer, Vector, Calendar, Date and
others.
java.text
– Must imported explicitly.
– Provides numeric formatting classes such as:
• Format, NumberFormat 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,
variableName is understood to be this.variableName
Example in the Auto class:
modelName is understood to be this.modelName
15
Using this in a Mutator Method
public void setInstanceVariable(
dataType instanceVariableName )
{
this.instanceVariableName = instanceVariableName;
}
Example:
public void setModel( 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 AutoClient class (which uses class
Auto) we instantiate an object:
– Auto a1=new Auto(); (globally -outside any
method)
– Suppose that we create a new method that it is
responsible for setting the instance fields of a1
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 folder1.folder2;
import folder1.folder2.folder3.Auto;
public class AutoClient
{
Auto a1=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 AutoClient
AutoClient ac=new AutoClient();
ac.usingThis();
Auto a2=new Auto("Infinity", “Jim”, 150, 18);
System.out.println(a2.toString());
a2.setCurrentID(15);
System.out.println(“the value of x ia:”+ac.x);
}
public void usingThis()
{
a1.setCurrentID(15);
int x=a1.getCurrentID();
System.out.println("The current id for a1 is now"+" "+this.x);
System.out.println("The value of the current id variable for object a1 is"+" "+x);
}
}
18
Using this
• The output of the previous program is:
C:\CS116\FALL2010\PracticeExercises\Lecture 2\ExampleUsingthis>javac -d
. AutoClient.java
C:\CS116\FALL2010\PracticeExercises\Lecture 2\ExampleUsingthis>java
folder1.folder2.AutoClient
The current id for a1 is now 300
The value of the current id variable for object a1 is15
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 AutoClient.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 auto1
and auto2:
if ( auto1.equals( auto2 ) )
System.out.println( "auto1 equals auto2" );
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 toString
and equals methods of the Object class.
• However, quite often we create (as we know) our own
toString 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:
objectReference instanceof ClassName
evaluates to true if objectReference is of
ClassName 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 objAuto = ( Auto ) o;
if ( this.modelName.equals( objAuto.modelName )
&&this.milesDriven== objAuto.milesDriven
&& Math.abs( this.mileage - objAuto.mileage )
< 0.0001 )
return true;
else
return false;
}
}
See text Examples 7.10 Auto.java and 7.11 AutoClient.java
24
Auto Class equals Method
(method overriding of Object class’ equals method).
• When in the AutoClient class we compare two
objects i.e. auto1 and auto2 of Auto class as in
the statement
if (auto1.equals(auto2))
this.modelName in the equals method refers
to the value of instance variable modelName
of auto1 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 firstName;
static int I d;
int currentid;
public Person()
{
firstName="John";
id++;
currentid=id;
}
public void method1()
{
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 method1() 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 PersonClient
{
public static void main(String[] args)
{
Person p1=new Person();
Person p2=new Person();
p1.method1();
p2.method1();
}
}
What is the output ?
29
Example of Class vs Local scope
• ---------- for object p1 ---------– The local value of currentid is 2
– The class scope of variable currentid is 1
• ---------- for object p2 ---------– 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 EnumName { obj1, obj2,… 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
compareTo( Enum eObj )
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 eObj )
returns true if this object is equal to the
argument eObj; returns false otherwise
String
toString( )
returns the name of the enum constant
33
Example enum
enum PersonType { ADULT_MALE, CHILD_MALE, ADULT_FEMALE, CHILD_FEMALE };
public class Persons
{
PersonType pt;
String firstName;
static int id;
int currentid;
public Persons()
{
firstName="John";
id++;
currentid=id;
}
public void setPersonType(PersonType pertyp)
{
this.pt=pertyp;
}
public PersonType getPersonType()
{
return pt;
}
}
34
Example enum
public class PersonsClient
{
public static void main(String[] args)
{
Persons p1=new Persons();
Persons p2=new Persons();
p1.setPersonType(PersonType.ADULT_FEMALE);
p2.setPersonType(PersonType.CHILD_MALE);
System.out.println("p1 is of person type:"+" "+p1.getPersonType());
System.out.println("p2 is of person type:"+" "+p2.getPersonType());
}
}
35
Example enum
– ---------- Output ---------– p1 is of person type: ADULT_FEMALE
– p2 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 firstName provides the first name of a Person
*/
String firstName;
static int id;
int currentid;
public Person()
{
firstName="John";
id++;
currentid=id;
}
39
Output html File
•
•
•
•
•
•
•
•
•
Package Class Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes 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 method1()
Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll,
toString, wait, wait, wait
Constructor Detail Person
public Person() Method Detail method1
public void method1() Package Class Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
40
Examples
• If you click on the Examples link next to
lecture2.ppt link ( in the Lectures page of the
course’ s web site) you will access example
files dealing with javadocs and enumeration.
41
STUDY GUIDE
• Read Chapter 7
– Section 7.9
– Section 7.10
– Section 7.13
– Section 7.15
– Section 7.16
42
Download