Download class

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to Java
Chapter 7
Classes and Object-Oriented Programming
Chapter 7 - Classes & Object-oriented Programming
1
Introduction to Java
Classes
• A class is the basic unit of the Java language. It is
the “blueprint” for the objects created from that
class.
• Each class contains some data definitions (called
fields), together with methods to manipulate that
data.
– When the object is instantiated from the class, an
instance variable is created for each field in the class.
• The methods serve as an interface to isolate the
data in the class from the outside world.
Chapter 7 - Classes & Object-oriented Programming
2
Introduction to Java
Class Hierarchy
• All classes form a part of a class hierarchy.
– Classes below a given class are subclasses of the class.
– Classes above a given class are superclasses of the
class. The class immediately above a given class is
known as its immediate superclass.
• A class inherits both instance variables and
methods from it’s immediate superclass. It can
add additional variables and methods, and it can
override (change) the inherited methods.
Chapter 7 - Classes & Object-oriented Programming
3
Introduction to Java
Structure of a Class
• The major components (members) of a class are:
– Fields - define the instance variables to be created
when an object is instantiated from the class.
– Constructors - special methods the define how to
initialize variables when an object is instantiated.
– Methods - implement the behaviors of a class.
– Finalizer - a special method to perform cleanup before
an object is destroyed.
Chapter 7 - Classes & Object-oriented Programming
4
Introduction to Java
The Member Access Operator (.)
• The members of a class (instance variables and
methods) are accessed using the member access
operator, or dot operator (.)
– To access a member, the user names a reference to a
object, followed by the dot operator, and followed by
the member name (with no spaces)
• Examples:
Obj.a
Obj.methodA
Access instance variable a
Access method methodA
Chapter 7 - Classes & Object-oriented Programming
5
Introduction to Java
Example: Timer Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Timer {
Class definition
// Define instance variables
private double savedTime;
// Saved start time in ms
// Define class constructor
public Timer() {
resetTimer();
}
Instance variable
definition
// ResetTimer() method
public void resetTimer() {
savedTime = System.currentTimeMillis();
}
Constructor
// elapsedTime() method returns elapsed time in seconds
public double elapsedTime() {
double eTime;
eTime = (System.currentTimeMillis() - savedTime) / 1000;
return eTime;
}
Method
resetTimer
}
Note: This method does
not have a finalizer.
Method
elapsedTime
Chapter 7 - Classes & Object-oriented Programming
6
Introduction to Java
Scope
• Instance variables have class scope, meaning that
they are visible everywhere within a class,
including within methods
– Example: variable savedTime in class Timer.
• Local variables within a method have block
scope, meaning that they are only visible within
the block in which they are defined.
– Example: variable eTime in method elapsedTime.
Chapter 7 - Classes & Object-oriented Programming
7
Introduction to Java
Hidden Instance Variables
• It is possible for a local variable to have the same
name as an instance variable, hiding it within a
block.
• In this case, the hidden instance variable can be
accessed using the this reference. Instance variables
// Define instance variables
private double x;
// x position of point
private double y;
// y position of point
public void setPoint(double x, double y) {
this.x = x;
this.y = y;
}
Local variables
Reference hidden
instance variables
using this
Chapter 7 - Classes & Object-oriented Programming
8
Introduction to Java
Common Types of Methods Found
in a Class
• Certain type of methods are common to many classes
– “set methods” are used to set the values of instance
variables
– “get methods” are used to read the values of instance
variables
– predicate methods return a true/false result based on
some test.
– toString method creates a string representation of the
contents of the object
Chapter 7 - Classes & Object-oriented Programming
9
Introduction to Java
Packages
• A package is a group of classes and methods that
share some related purpose.
• All standard Java classes are grouped in packages,
such as java.lang, java.io, etc.
• To use the contents of any package except
java.lang, it must first be imported into a
program with an import statement.
• The import statements must be the first noncomment lines in a program!
Chapter 7 - Classes & Object-oriented Programming
10
Introduction to Java
Creating Your Own Packages
• You can create packages for your own methods:
– First, add a package statement to each class specifying
the package that it belongs to. Place the statement
before the class definition:
package chapman.testpackage;
– Then, compile using the -d option to specify the root
directory of the package structure:
javac -d d:\packages MyClass.java;
– These commands will place file MyClass.class in
directory d:\packages\chapman\testpackage.
Chapter 7 - Classes & Object-oriented Programming
11
Introduction to Java
Example Creating MyClass
package statement
// Class to test creating and using a package
package chapman.testpackage;
// Place in testpackage
public class MyClass {
// Method mySum
public int mySum(int a, int b) {
return a + b;
}
}
D:\>javac –d d:\packages MyClass.java
Compilation
statement
The class file will now be in directory
d:\packages\chapman\testpackage
Chapter 7 - Classes & Object-oriented Programming
12
Introduction to Java
Using Your Own Packages
• To use the classes in your packages, you must add
an import statement to each class wanting to
access the packages.
• In addition, you must add the root directory of the
package structure to the CLASSPATH environment
variable.
• Example: If class chapman.testpackage.MyClass is in
directory d:\package\chapman\testpackage, then the
root directory of the package structure is d:\package, and
it must appear in a CLASSPATH statement.
Chapter 7 - Classes & Object-oriented Programming
13
Introduction to Java
Example Using MyClass
set CLASSPATH=.;d:\packages
Set class path in
environment
// Class to test using a package
import chapman.testpackage.*;
public class TestMyClass {
// Define the main method to test MyClass
public static void main(String[] args) {
import
statement
// Declare variables
int i = 8, j = 6;
// Instantiate a MyClass object
MyClass c = new MyClass();
// Use the object
System.out.println("i + j = " + c.mySum(i,j));
}
}
Chapter 7 - Classes & Object-oriented Programming
14
Introduction to Java
Member Access Modifiers
• Member access modifiers control where a class
member can be accessed from:
– public: Members can be accessed from any class
– private: Members can only be accessed from within
the class that they are defined in
– <none>: With no modifier, members can be accessed
from any class in the same package as the class that
they are defined in.
– protected: Access from the same package or from
any subclass of the class that they are defined in
Chapter 7 - Classes & Object-oriented Programming
15
Introduction to Java
Finalizers
• A finalizer is a special method named finalize,
which performs any necessary clean-up (releasing
resources, etc.) before an object is destroyed.
• It is automatically called just before an object is
destroyed.
• Most classes do not need a finalizer.
Chapter 7 - Classes & Object-oriented Programming
16
Introduction to Java
Garbage Collection
• When an object is no longer needed, it is
automatically destroyed by a low-priority thread
called the garbage collector.
• Destroying old objects returns their resources to
the system for re-use.
• Any object that no longer has a reference pointing
to it is a candidate for garbage collection.
• The garbage collector calls a class’s finalizer
before destroying it.
Chapter 7 - Classes & Object-oriented Programming
17
Introduction to Java
Static Variables
• A static variable is a special type of variable that
is shared by all objects instantiated from a class.
• Static variables are useful for keeping track of
global information such as the number of objects
instantiated from a class, etc.
• They are declared with the static keyword:
private static int created;
// Static!
• Static variables are also useful for declaring a
single shared copy of a constant:
static final double C = 2.99792458e8;
Chapter 7 - Classes & Object-oriented Programming
18
Introduction to Java
Example
Class A definition
with two instance
variables and one
static variable
Instance
variables:
x,y
Static:
z
Methods
Inherited
Method(s)
Constructors
Methods
x an y are unique
Fields:
x,y
Static:
z
in each object,
while s is
common to both
Object a1
Methods
Inherited
Method(s)
Constructors
Methods
Instance
variables:
x,y
Static:
z
Methods
Class A
Inherited
Method(s)
Constructors
Methods
Two objects a1 and a2
instantiated from class A
Object a2
Chapter 7 - Classes & Object-oriented Programming
19
Introduction to Java
Static Methods
• Static methods are methods that can be executed
without first instantiating an object of the class
containing the method.
• Static methods can access the static variables in a
class, but they cannot access instance variables.
• Static methods are normally used for utility
calculations that are independent of the data in a
class, such as sin(), cos(), tan(), etc.
Chapter 7 - Classes & Object-oriented Programming
20
Introduction to Java
Example: Extended Math Class
// Specify package for class
package chapman.math;
public class ExMath {
// Define class variables
final static private double LOGE_10 = 2.302585092994046;
static
// Hyperbolic sine method
public static double sinh ( double x ) {
return ( (Math.exp(x) - Math.exp(-x)) / 2 );
}
variable
static methods
...
// Logarithm to the base 10
public static double log10 ( double x ) {
return ( Math.log(x) / LOGE_10 );
}
}
Chapter 7 - Classes & Object-oriented Programming
21