Tải bản đầy đủ (.ppt) (32 trang)

Chapter 3 Writing classes

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (715.47 KB, 32 trang )

Writing Classes
Writing Classes
Chapter 3
Chapter 3
1
Out lin e

Introduction to Object-Oriented Programming (OOP)

Writing a Java class

Encapsulation and accessor methods
2
Procedural Programming
Procedural Programming


and
and
Object-Oriented Programming
Object-Oriented Programming

Procedural Programming consists of designing a set of
functions (or algorithms) to solve a problem

Algorithms + Data Structures = Programs

Object-Oriented Programming (OOP) puts data first, then
looks at the algorithms that operate on the data
3
Concepts in OOP


Concepts in OOP

Class

A class is the model, pattern, or blueprint from which
objects are actually made

A class means a category of things

A class can be used in Java as the data type

Object

Object means a particular item that belongs to a class

Object also called an “instance”

Example:

String s1 = "Hello";
Here, String is the class, and the variable s1 is objects (or
“instances of the String class”)
4
Concepts in OOP
Concepts in OOP
(cont.)
(cont.)

Attributes


The properties that describe an object

Behaviors

Activities of an object

Each object has a set of attributes (state) and a set of
behaviors
5
 2003 Prentice Hall, Inc. All rights reserved.
Example: Class and Object
Class: Ball
Attributes: radius,
color
Behavior: thrown,
bounced, rolled
Object1
radius = 5
color = red
thrown,
bounced,
rolled
Object3
radius = 3
color = green
thrown,
bounced,
rolled
Object2
radius = 10

color = blue
thrown,
bounced,
rolled
6
Examples
Examples

List attributes and behaviors of students

Student code, name, gender, birthday, birthplace, class,
grade 1, grade 2,…

Calculate average grade, view grade, pay tuition,…

Suppose that you write a program to calculate area and
perimeter of a rectangle. Find objects and list attributes and
behaviors of them

Object: Rectangle

Attributes: width, height

Behaviors: Calculate area, calculator perimeter
7
Examples
Examples


(cont.)

(cont.)

Suppose that you want to write a program to monthly pay the
employees of a company. Paying employees based on
products they made, in addition, you have to compute Social
Security and Medicare taxes. Find objects and list attributes
and behaviors of them

Object: Employee

Attributes: employee number, name, address, social
security number, products,…

Behaviors: compute employee pay, compute employee
Social Security and Medicare taxes, mail employee a
paycheck once a month,…
8
Objects model
Objects model
ClassName
- Attributes
+ Behaviors
Properties
Data
Fields
Variables
Instance data
Methods
9
Objects model:

Objects model:
Example
Example
Rectangle
-
width
-
height
+ Calculate area
+ Calculator perimeter
Student
-
Student code
-
Name
-
Gender
-
Birthday
-
Birthplace
-
Class
-
Grade 1
-
Grade 2
+ Calculate average
+ View grade
+ Pay tuition

10
Out lin e

Introduction to Object-Oriented Programming (OOP)

Writing a Java class

Encapsulation and accessor methods
11
Writing a Java Class
Writing a Java Class
class ClassName
{
property1
property2
. . .
constructor1
constructor2
. . .
method1
method2
. . .
}
12
Writing class Rectangle
Writing class Rectangle
class ClassName
{
property1
property2

. . .
constructor1
constructor2
. . .
method1
method2
. . .
}
class Rectangle
{
double width;
double height;

public double getArea()
{
return width*height;
}

public double getPerimeter()
{
return (width+height)*2;
}
}
Rectangle
-
width: double
-
height: double
+ getArea() : double
+ getPerimeter() : double

13
Writing class Student
Writing class Student
class Student{
String studentCode, name, birthplace,
classID;
boolean gender;
Date birthday;
double grade1, grade2;
public double getAverage() {
return (grade1+ grade2)/2;
}
public void viewGrade() {
System.out.println( studentCode + “\t”+
name + ”\t”+ birthday + ”\t”+ birthplace + ”\t”+
classID + ”\t”+ getAverage() );
}
}
class NameOfClass
{
attribute1
attribute2
. . .
constructor1
constructor2
. . .
method1
method2
. . .
}

Student
-
studentCode: String
-
name: String
-
gender: boolean
-
birthday: Date
-
birthplace: String
-
classID: String
-
grade1: double
-
grade2: double
+ getAverage(): double
+ viewGrade(): void
14
Declaring objects
Declaring objects

Once a class is defined, you can declare variables (object
reference) of that type
Rectangle r1, r2;
Student st;

Object references are initially null


The null value is a distinct type in Java and is not equal to
zero

To explicitly create the object, you must use the new operator
Rectangle r = new Rectangle();
st = new Student();
ClassName objectName = new ClassName();
15
Accessing instance variables
Accessing instance variables

To access fields and methods of an object, using the dot
operator
objectName.fieldName
objectName.methodName(argumentsToMethod)

Example:
r.width = 10;
r.height = 5;
double x= r.getArea();
double y= r.getPerimeter();
16
Example: Writing class Rectangle (1)
Example: Writing class Rectangle (1)
public class Rectangle
{
double width, height;

public double getArea()
{

return width * height;
}
public double getPerimeter()
{
return (width+height) * 2;
}
}
Rectangle.java
public class RectangleTest
{
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.width = 10;
r.height = 5;
double area = r.getArea();
double peri = r.getPerimeter();
System.out.println("Area is "+ area);
System.out.println("Perimeter is "+ peri);
}
}
RectangleTest.java
Note: You almost always make instance variables private
and use methods to access them (see next content…)
In which case outside code can’t access them directly
17
Constructor
Constructor

Constructor is a special method called when a class is created
with new


Constructor is especially useful for supplying values of
fields

Constructors are declared through:

Notice that the constructor name must exactly match the
class name

Constructors have no return type (not even void)

A class can have multiple constructors
public ClassName (agrsList) {

}
18
Constructor
Constructor
(cont.)
(cont.)

Java automatically provides a zero-argument constructor
(default constructor) if and only if the class doesn’t define it’s
own constructor

That’s why you could say
Rectangle r = new Rectangle(); even though a constructor
was never defined

This default constructor sets all the instance fields to their

default values

All numeric data contained in the instance fields would be
0, all booleans would be false, and all object variables
would be set to null

If you have your own constructor, you should provide a default
constructor, it can do nothing
19
Example: Writing class Rectangle (2)
Example: Writing class Rectangle (2)
public class Rectangle
{
double width, height;
public Rectangle( double x,
double y )
{
width = x;
height = y;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return (width+height) * 2;
}
}
Rectangle.java
public class RectangleTest
{

public static void main(String[] args) {
Rectangle r = new Rectangle(10,5);
double area = r.getArea();
double peri = r.getPerimeter();
System.out.println("Area is "+ area);
System.out.println("Perimeter is "+ peri);
}
}
RectangleTest.java
Can write:
Rectangle r = new Rectangle(); ?
Class with Constructors
The
The
this
this
variable
variable

The this object reference can be used inside any non-static
method to refer to the current object

The common uses of the this reference are:

To pass a reference to the current object as a parameter to
other methods:
someMethod(this);

To resolve name conflicts


Using this permits the use of instance variables in methods
that have local variables with the same name

To call another constructor

In a class, a constructor can invoke other constructor, by
using this(agrs), note the this statement must appear
as the first line of code in the constructor (otherwise, a
compiler error will occur)
21
Example: Writing class Rectangle (3)
Example: Writing class Rectangle (3)
public class Rectangle
{
double width, height;
public Rectangle( double width,
double height )
{
this.width = width;
this.height = height;
}
public Rectangle()
{
this(0, 0);
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return (width+height) * 2;

}
}
Rectangle.java
public class RectangleTest
{
public static void main(String[] args) {
Rectangle r = new Rectangle();
double area = r.getArea();
double peri = r.getPerimeter();
System.out.println("Area is "+ area);
System.out.println("Perimeter is "+ peri);
r = new Rectangle(10, 5);
area = r.getArea();
peri = r.getPerimeter();
System.out.println("Area is "+ area);
System.out.println("Perimeter is "+ peri);
}
}
RectangleTest.java
Using this
22
Out lin e

Introduction to Object-Oriented Programming (OOP)

Writing a Java class

Encapsulation and accessor methods
23


Encapsulation is the technique of making the fields in
a class private and providing access to the
fields via public methods

Encapsulation is also referred to as data hiding

Encapsulation is one of the four fundamental OOP concepts.
The other three are inheritance, polymorphism, and
abstraction
Encapsulation
Encapsulation
Client (user)
Client (user)
Methods
Data
24
Encapsulation
Encapsulation
(cont.)
(cont.)

Instance variables should always be private

private variables can be accessed only by the methods
of the class

Providing accessor methods via public methods: get/set

Methods can be defined with public or private


public method: provide services to the client of the class
so that they can be invoked by the client  service
methods

private method: cannot be invoked from outside the
class. The only purpose of a private method is to help the
other methods of the class do their job  support methods
25

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×