1. Trang chủ
  2. » Giáo án - Bài giảng

Chapter 3 Writing classes

32 298 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Writing Classes
Định dạng
Số trang 32
Dung lượng 822 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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

Trang 1

Writing Classes

Chapter 3

1

Trang 2

• Encapsulation and accessor methods

2

Trang 3

Procedural Programming and

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

Trang 4

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”

• String s1 = "Hello";

Here, String is the class, and the variable s1 is objects (or

“instances of the String class”)

4

Trang 5

Concepts in OOP (cont.)

Trang 6

 2003 Prentice Hall, Inc All rights reserved.

Example: Class and Object

6

Trang 7

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

Trang 8

• 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

Trang 9

Fields Variables Instance data

Methods

9

Trang 10

Objects model: Example

Trang 11

• Encapsulation and accessor methods

11

Trang 12

Writing a Java Class

Trang 13

Writing 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

Trang 14

Writing class Student

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() );

} }

Trang 15

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

Trang 16

Accessing instance variables

To access fields and methods of an object, using the dot

operator

objectName.fieldName objectName.methodName(argumentsToMethod)

Trang 17

Example: Writing class Rectangle (1)

public class Rectangle

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

and use methods to access them (see next content…)

In which case outside code can’t access them directly 17

Trang 18

• 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

… }

18

Trang 19

Constructor (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

Trang 20

Example: Writing class Rectangle (2)

public class Rectangle

{

double width, height;

public Rectangle( doub le x,

double y ) {

width = x;

height = y;

}

public double getArea() {

return width * height;

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

Trang 21

The this variable

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

• 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

Trang 22

Example: Writing class Rectangle (3)

public class Rectangle

{

double width, height;

public Rectangle( double width,

double height ) {

public double getArea() {

return width * height;

Rectangle r = new Rectangle();

double area = r.getArea();

double peri = r.getPerimeter();

}

RectangleTest.java

Using this

22

Trang 23

23

Trang 24

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

Trang 25

Encapsulation (cont.)

• private variables can be accessed only by the methods

of the class

• Providing accessor methods via public methods: get/set

• 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

Trang 26

Example: Writing class Rectangle (4)

public class Rectangle

{

private double width, height;

public Rectangle (double width,

double height) {

} public void setHeight(double height) { this.height = height;

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

} public double getPerimeter() { return (width+height) * 2;

} }

26

Trang 27

Example: Writing class Rectangle (4)

{ public static void main( String [] args ) {

System.out.println("Area is "+ area);

System.out.println("Perimeter is "+ peri);

} }

RectangleTest.java

Write accessor methods

27

Trang 28

More details on Getters and Setters

There need not be both getters and setters

It is common to have fields that can be set at instantiation,

but never changed again (immutable field)

Getter/setter names need not correspond to instance variable names

public class Ship {

public Ship(…) {

shipName = …;

} public String getShipName() { return shipName; }

// No setShipName method

}

28

Trang 29

Note: Java naming conventions

Start classes with uppercase letters

Start other things with lowercase letters

• Instance variables, local variables, methods, parameters to

methods

public class MyClass {

public String firstName, lastName;

public String fullName() {

String name = firstName + " " + lastName;

return name;

} }

29

Trang 30

Class design hints

Always keep data private

Always initialize data

Don't use too many basic types in a class

• Example: Customer class

private String customerID;

private String customerName;

private String street;

private String city;

private String state;

private int zip;

Not all fields need individual field accessors and mutators

Make the names of your classes and methods reflect their

responsibilities

30 Create an Address class

Trang 31

Syntax to create a class in Java?

What is constructor? How many constructors can we have in a class?

Why to make all instance variables private?

How to access private instance variables?

Write a class to calculate area of a circle with radius Test this class

31

Trang 32

Read more

32

Ngày đăng: 13/05/2014, 10:42

TỪ KHÓA LIÊN QUAN