Chapter 7 Review

advertisement
Chapter 7 Objects and Classes
1
Fall 2012 CS2302: Programming Principles
Content







2
Classes and Objects
How to define classes
Reference Type and default value
Using classes from the java library
Visibility Modifiers
Data Field Encapsulation
Static variables
Fall 2012 CS2302: Programming Principles
Classes and Objects



A Java program consists of one or more
classes
A class is an abstract description of objects
Here is an example class:
–

3
class Dog { ...description of a dog goes here... }
Here are some objects of that class:
Fall 2012 CS2302: Programming Principles
More Objects


4
Here is another example of a class:
– class Window { ... }
Here are some examples of Windows:
Fall 2012 CS2302: Programming Principles
OO Programming Concepts

Object-oriented programming (OOP)
involves programming using objects.
–
–
5
A class is a piece of the program’s source
code that describes a particular type of
objects.
An object is called an instance of a class. A
program can create and use more than one
object (instance) of the same class.
Fall 2012 CS2302: Programming Principles
Class



6
A blueprint for
objects of a
particular type
Defines the
structure (number,
types) of the
attributes
Defines available
behaviors of its
objects
Fall 2012 CS2302: Programming Principles
Object
Attributes
Behaviors
Class: Car

Attributes:








String model
Color color
int numPassengers
double amountOfGas
Behaviors:

7
Object: a car
Add/remove a passenger
Get the tank filled
Report when out of gas
Fall 2012 CS2302: Programming Principles
Attributes:





model = "Mustang"
color = Color.YELLOW
numPassengers = 0
amountOfGas = 16.5
Behaviors:
Defining Classes for Objects

Class
–

Object
–
–

User-defined data type
Instance of class, A role of variable
Define a correspond class to define a object
Define a class
Describe the structure of object
Data Field(variable, constant)
[modifier] class ClassName {
// field declarations
public, final,
//Constructors
abstract
// method declarations Define actions of object
}
Method Field
8
Fall 2012 CS2302: Programming Principles
Constructors
9

Short procedures for creating objects of a class

Always have the same name as the class

Initialize the object’s fields

May take parameters, but no returns

A class may have several constructors that differ in
the number and/or types of their parameters
Fall 2012 CS2302: Programming Principles
Class Example
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
Data field
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
10
Fall 2012 CS2302: Programming Principles
Method
Object Example
Public class TestCircle {
/** Main method */
Public static void main(String[] args){
/** Create a circle with radius 1.0*/
Circle circle1 = new Circle();
System.out.println(“The area of the
Circle is ” + circle1.getArea());
Create Object
Access Method
/** Create a circle with radius 25*/
Circle circle2 = new Circle(25);
System.out.println(“The area of the
Circle is ” + circle2.getArea());
/** Modify circle radius */
circle2.radius = 100;
System.out.println(“The area of the
Circle is ” + circle2.getArea());
}
11
Fall 2012 CS2302: Programming Principles
Access Data
Class


12
A piece of the
program’s source
code
Written by a
programmer
Fall 2012 CS2302: Programming Principles
vs.
Object

An entity in a running
program

Created when the
program is running
(by the main method
or a constructor or
another method)
Class
13
vs.
Object

Specifies the
structure (the number
and types) of its
objects’ attributes —
the same for all of its
objects

Holds specific values
of attributes; these
values can change
while the program is
running

Specifies the possible
behaviors of its
objects

Behaves
appropriately when
called upon
Fall 2012 CS2302: Programming Principles
Diagram of program structure
Program
File
File
Class
File
Variables
Constructors
Variables
File
Statements
Methods
Variables
Statements


14
Fall 2012 CS2302: Programming Principles
A program consists
of one or more
classes
Typically, each class
is in a separate .java
file
Object type is a Reference Type

15
Go over the textbook slides from page 29 to 38
Fall 2012 CS2302: Programming Principles
Encapsulation
Encapsulation
is one of the four fundamental OOP concepts.
The other three are inheritance (is the capability of a class to use the
properties and methods of another class), polymorphism (more than one
form), and abstraction (simplifying complex reality by modeling classes ).
Encapsulation
can be described as a protective barrier that
prevents the code and data being randomly accessed by other code
defined outside the class. Access to the data and code is tightly
controlled by an interface.
Encapsulation
provides a technique of making the fields in a
class private and providing access to the fields via public
methods.
16
Fall 2012 CS2302: Programming Principles
Benefits of Encapsulation

The fields of a class can be made read-only or
write-only.

A class can have total control over what is stored
in its fields.

The users of a class do not know (like a blackbox)
how the class stores its data. A class can change
the data type of a field, and users of the class do
not need to change any of their code.
17
Fall 2012 CS2302: Programming Principles
Encapsulation Implementation

If a field is declared private, it cannot be accessed
by anyone outside the class, thereby hiding the fields
within the class. For this reason, encapsulation is also
referred to as data hiding.

A class interacts with other classes only through
constructors and public methods

Other classes do not need to know the mechanics
(implementation details) of a class to use it effectively
example of Encapsulation
18
Fall 2012 CS2302: Programming Principles
Visibility Modifiers






19
We accomplish encapsulation through the
appropriate use of visibility modifiers
Visibility modifiers specify which parts of the
program may see and use any particular
class/method/field
A modifier is a Java reserved word that specifies
particular characteristics of a programming construct
We've used the modifier final to define a constant
Java has three visibility modifiers: public,
private, and protected
We will discuss the protected modifier later in the
course
Fall 2012 CS2302: Programming Principles
Visibility Modifiers - Classes




20
A class can be defined either with the public
modifier or without a visibility modifier.
If a class is declared as public it can be used by
any other class
If a class is declared without a visibility modifier
it has a default visibility. The default modifier
restricts access to the same package.
Classes that define a new type of objects, that
are supposed to be used anywhere, should be
declared public.
Fall 2012 CS2302: Programming Principles
Visibility Modifiers - Members
A member is a field, a method or a constructor of
the class.
Members of a class can be declared as
private, protected, public or without a
visibility modifier:





21
private int hours;
int hours;
public int hours;
Fall 2012 CS2302: Programming Principles
Public Visibility



22
Members that are declared as public can be
accessed from any class that can access the
class of the member
Example: the methods getHours(),
secondElapsed() and setTime() are part of
the interface of class Clock so we define them
as public.
We do not want to reveal the internal
representation of the object’s data. So we
usually declare its state variables as private
(encapsulation).
Fall 2012 CS2302: Programming Principles
Private Visibility



23
A class member that is declared as private,
can be accessed only by code that is within the
class of this member.
We hide the internal implementation of the class
by declaring its state variables and auxiliary
methods as private.
Data hiding is essential for encapsulation.
Fall 2012 CS2302: Programming Principles
Illegal Access - example
// Example of illegal access
class BankAccountTest {
public static void main(String[] args) {
BankAccount victim = new BankAccount(2398742);
victim.balance = victim.balance - 500;
// this will not compile!
}
}
public class BankAccount {
private long accountNumber;
private double balance;
// …
24
Fall 2012 CS2302: Programming Principles
Encapsulation - example
public void transfer(double amount,
BankAccount targetAccount) {
withdraw(amount);
targetAccount.deposit(amount);
}
// alternative version (valid, but not so nice)
public void transfer(double amount,
BankAccount targetAccount) {
balance -= amount;
targetAccount.balance += amount;
}
25
Fall 2012 CS2302: Programming Principles
Getters/Accessors and Setters/Mutators Methods
class Clock {
Private String time;
void setTime (String t) {time = t;}
String getTime() {return time;}
}
class ClockTestDrive {
public static void main (String [] args){
Cock c = new Clock();
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod); }
27
}
Fall 2012 CS2302: Programming Principles
Encapsulation


Constructors and methods can call other
public and private methods of the same class.
Constructors and methods can call only
public methods of another class.
Class
private


27
X
Class
field
public method

public method
private method

Fall 2012 CS2302: Programming Principles
Y
The Static Modifier
28

The static modifier can be applied to
variables or methods.

It associates a variable or method with the
class rather than an object.

Methods that are declared as static do not
act upon any particular object. They just
encapsulate a given task, a given algorithm.
Fall 2012 CS2302: Programming Principles
Static Variables

It is a variable which belongs to the class and
not to object (instance) --- class variable

A single copy to be shared by all instances of
the class

A static variable can be accessed directly by
the class name and doesn’t need any object
–
29
Syntax : <class-name>.<variable-name>
Fall 2012 CS2302: Programming Principles
Static Methods
31

It is a method which belongs to the class and not to the
object(instance)

A static method can access only static data. It can not access
non-static data (instance variables)

A static method can call only other static methods and can not call
a non-static method from it.

A static method can be accessed directly by the class name and
doesn’t need any object
– Syntax : <class-name>.<method-name>

A static method cannot refer to “this” or “super” keywords in anyway
Fall 2012 CS2302: Programming Principles
Static Variables - Example
public class BankAccount {
private long accountNumber;
private double balance;
private static int numberOfAccounts = 0;
public BankAccount() {
this.accountNumber = ++numberOfAccounts;
this.balance = 0;
}
public static int getNumberOfAccounts {
return numberOfAccounts;
}
30
}
Fall 2012 CS2302: Programming Principles
Summary


A program consists of one or more classes
A class is a description of a kind of object
–

A class describes data, constructors, and
methods
–
–
–

32
In most cases, it is the objects that do the actual work
An object’s data is information about that object
An object’s methods describe how the object behaves
A constructor is used to create objects of the class
Methods (and constructors) may contain
temporary data and statements (commands)
Fall 2012 CS2302: Programming Principles
Download