21
Chapter 7 - Classes & Object-oriented Programming 1 Introduction to Java Chapter 7 Classes and Object-Oriented Programming

Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Embed Size (px)

Citation preview

Page 1: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 1

Introduction to Java

Chapter 7

Classes and Object-Oriented Programming

Page 2: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 2

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.

Page 3: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 3

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.

Page 4: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 4

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.

Page 5: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 5

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 Access instance variable a

Obj.methodA Access method methodA

Page 6: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 6

Introduction to Java

Example: Timer Class

Method resetTimer

Class definition 1 public class Timer { 2 3 // Define instance variables 4 private double savedTime; // Saved start time in ms 5 6 // Define class constructor 7 public Timer() { 8 resetTimer(); 9 }1011 // ResetTimer() method12 public void resetTimer() {13 savedTime = System.currentTimeMillis();14 }1516 // elapsedTime() method returns elapsed time in seconds17 public double elapsedTime() {18 double eTime;19 eTime = (System.currentTimeMillis() - savedTime) / 1000;20 return eTime;21 }22 }

Instance variable definition

Constructor

Method elapsedTime

Note: This method does not have a finalizer.

Page 7: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 7

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.

Page 8: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 8

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.

// 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; }

Instance variables

Local variables

Reference hidden instance variables using this

Page 9: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 9

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

Page 10: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 10

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 non-comment lines in a program!

Page 11: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 11

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.

Page 12: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 12

Introduction to Java

Example Creating MyClass

// Class to test creating and using a packagepackage chapman.testpackage; // Place in testpackagepublic class MyClass {

// Method mySum public int mySum(int a, int b) { return a + b; }}

D:\>javac –d d:\packages MyClass.java

package statement

Compilation statement The class file will now be in directory d:\

packages\chapman\testpackage

Page 13: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 13

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.

Page 14: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 14

Introduction to Java

Example Using MyClassSet class path in environment

import statement

set CLASSPATH=.;d:\packages

// Class to test using a packageimport chapman.testpackage.*;public class TestMyClass {

// Define the main method to test MyClass public static void main(String[] args) {

// 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)); }}

Page 15: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 15

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

Page 16: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 16

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.

Page 17: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 17

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.

Page 18: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 18

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;

Page 19: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 19

Introduction to Java

Example

Constructors

Methods

Inherited

Method(s)

Fields:x,y

Static:z M

ethods

C la ss A

O bje c t a1

Constructors

Methods

Inherited

Method(s) Instance

variables:x,y

Static:z M

ethods

O b je c t a2

Constructors

MethodsInherited

Method(s) Instance

variables:x,y

Static:z M

ethods

Class A definition with two instance variables and one static variable

x an y are unique in each object, while s is common to both

Two objects a1 and a2 instantiated from class A

Page 20: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 20

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.

Page 21: Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming

Chapter 7 - Classes & Object-oriented Programming 21

Introduction to Java

Example: Extended Math Class

// Specify package for classpackage chapman.math;

public class ExMath {

// Define class variables final static private double LOGE_10 = 2.302585092994046;

// Hyperbolic sine method public static double sinh ( double x ) { return ( (Math.exp(x) - Math.exp(-x)) / 2 ); }

...

// Logarithm to the base 10 public static double log10 ( double x ) { return ( Math.log(x) / LOGE_10 ); }}

static methods

static variable