java cơ bản java co ban

Post on 26-May-2015

311 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Java cơ bản, b

TRANSCRIPT

Introduction toJava Programming

Y. Daniel LiangEdited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltd

https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltd

VTC Academy THSoft Co.,Ltd 2

Introduction

Course Objectives Organization of the Book

VTC Academy THSoft Co.,Ltd 3

Course Objectives Upon completing the course, you will understand

– Create, compile, and run Java programs

– Primitive data types

– Java control flow

– Methods– Arrays (for teaching Java in two semesters, this could be the end)

– Object-oriented programming

– Core Java classes (Swing, exception, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework)

VTC Academy THSoft Co.,Ltd 4

Course Objectives, cont.

You will be able to – Develop programs using Eclipse IDE– Write simple programs using primitive data

types, control statements, methods, and arrays.– Create and use methods– Write interesting projects

VTC Academy THSoft Co.,Ltd 5

Session 03: Method and Class

Methods Object-Oriented Programming Classes Packages Subclassing and Inheritance Polymorphism

VTC Academy THSoft Co.,Ltd 6

Introducing Methods

Method StructureA method is a collection of statements that are grouped together to perform an operation.

VTC Academy THSoft Co.,Ltd 7

Introducing Methods, cont.•parameter profile refers to the type, order, and number of the parameters of a method.

•method signature is the combination of the method name and the parameter profiles.

•The parameters defined in the method header are known as formal parameters.

•When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters.

VTC Academy THSoft Co.,Ltd 8

Declaring Methods

public static int max(int num1, int num2) {

if (num1 > num2) return num1; else return num2;}

VTC Academy THSoft Co.,Ltd 9

Calling Methods, cont.

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); }

public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

pass i pass j

VTC Academy THSoft Co.,Ltd 10

Calling Methods, cont.

The main method i: j: k:

The max method num1: num2: result:

pass 5

5

2

5

5

2

5

pass 2 parameters

VTC Academy THSoft Co.,Ltd 11

CAUTION

A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }

To fix this problem, delete if (n<0) in the code.

VTC Academy THSoft Co.,Ltd 12

Actions on Eclipse

Open Eclipse IDE– Create project: Session3Ex– Create package: com.vtcacademy.exopp– Create java class: Ex3WithOpp.java (with main method)– Create java class: Circle.java

RunRunSourceSource

VTC Academy THSoft Co.,Ltd 13

The Math Class Class constants:

– PI– E

Class methods: – Trigonometric Methods – Exponent Methods– Rounding Methods– min, max, abs, and random Methods

VTC Academy THSoft Co.,Ltd 14

Trigonometric Methods

sin(double a)

cos(double a)

tan(double a)

acos(double a)

asin(double a)

atan(double a)

VTC Academy THSoft Co.,Ltd 15

Exponent Methods exp(double a)

Returns e raised to the power of a.

log(double a)

Returns the natural logarithm of a.

pow(double a, double b)

Returns a raised to the power of b.

sqrt(double a)

Returns the square root of a.

VTC Academy THSoft Co.,Ltd 16

Rounding Methods double ceil(double x)

x rounded up to its nearest integer. This integer is returned as a double value.

double floor(double x)x is rounded down to its nearest integer. This integer is returned as a double value.

double rint(double x)x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.

int round(float x)Return (int)Math.floor(x+0.5).

long round(double x)Return (long)Math.floor(x+0.5).

VTC Academy THSoft Co.,Ltd 17

min, max, abs, and random

max(a, b)and min(a, b)Returns the maximum or minimum of two parameters.

abs(a)Returns the absolute value of the parameter.

random()Returns a random double valuein the range [0.0, 1.0).

VTC Academy THSoft Co.,Ltd 18

Example 3.1 Computing Mean and Standard Deviation

Generate n random numbers and compute the mean and standard deviation

n

xmean

n

ii

1

1

)(

1

2

12

nn

xx

deviation

n

i

n

ii

i

VTC Academy THSoft Co.,Ltd 19

Example 3.2 Obtaining Random Characters

Write the methods for generating random characters. The program uses these methods to generate 175 random characters between ‘!' and ‘~' and displays 25 characters per line. To find out the characters between ‘!' and ‘~', see Appendix B, “The ASCII Character Set.”

VTC Academy THSoft Co.,Ltd 20

OO Programming Concepts

data field 1

method n

data field n

method 1

An object

...

...

State

Behavior

Data Field radius = 5

Method findArea

A Circle object

VTC Academy THSoft Co.,Ltd 21

Class and Objects

circle1: Circle

radius = 2

new Circle()

circlen: Circle

radius = 5

new Circle()

...

UML Graphical notation for classes

UML Graphical notation for objects

Circle

radius: double

findArea(): double

UML Graphical notation for fields

UML Graphical notation for methods

Illustration on code

VTC Academy THSoft Co.,Ltd 22

Class Declaration

class Circle { double radius = 1.0;

double findArea(){ return radius * radius * 3.14159; }}

VTC Academy THSoft Co.,Ltd 23

Declaring Object Reference Variables

ClassName objectReference;

Example:Circle myCircle;

VTC Academy THSoft Co.,Ltd 24

Creating Objects

objectReference = new ClassName();

Example:myCircle = new Circle();

The object reference is assigned to the object reference variable.

VTC Academy THSoft Co.,Ltd 25

Declaring/Creating Objectsin a Single Step

ClassName objectReference = new ClassName();

Example:Circle myCircle = new Circle();Circle myCircle2;

VTC Academy THSoft Co.,Ltd 26

Constructors

Circle(double r) { radius = r;}

Circle() { radius = 1.0; }

myCircle = new Circle(5.0);

Constructors are a special kind of methods that are invoked to construct objects.

VTC Academy THSoft Co.,Ltd 27

Constructors

Circle(double r) { radius = r;}

Circle() { radius = 1.0; }

myCircle = new Circle(5.0);

Constructors are a special kind of methods that are invoked to construct objects.

VTC Academy THSoft Co.,Ltd 28

Constructors, cont.A constructor with no parameters is referred to as a default constructor.

       Constructors must have the same name as the class itself.

       Constructors do not have a return type—not even void.

       Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.

VTC Academy THSoft Co.,Ltd 29

Example 3.3 Using Classes from the Java Library

Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax.swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames.

Illustration on code

VTC Academy THSoft Co.,Ltd 30

Subclassing and Inheritance

private None protected Public

Illustration on code

VTC Academy THSoft Co.,Ltd 31

Example 3.4

Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron

VTC Academy THSoft Co.,Ltd 32

Example 3.4

http://blogs.unsw.edu.au/comp1400/blog/2011/09/tut-10/

VTC Academy THSoft Co.,Ltd 33

Abstract Classes and Methods

Abstract classes – Are superclasses (called abstract superclasses)– Cannot be instantiated – Incomplete

subclasses fill in "missing pieces"

Concrete classes– Can be instantiated– Implement every method they declare– Provide specifics

VTC Academy THSoft Co.,Ltd 34

Abstract Classes and Methods (Cont.)

Abstract classes not required, but reduce client code dependencies

To make a class abstract– Declare with keyword abstract– Contain one or more abstract methods

public abstract void draw();

– Abstract methods No implementation, must be overridden

VTC Academy THSoft Co.,Ltd 35

Abstract Classes and Methods (Cont.)

Application example– Abstract class Shape

Declares draw as abstract method

– Circle, Triangle, Rectangle extends Shape Each must implement draw

– Each object can draw itself

Iterators– Array, ArrayList (Chapter 22)

– Walk through list elements

– Used in polymorphic programming to traverse a collection

Illustration on code

VTC Academy THSoft Co.,Ltd 36

Case Study: Creating and Using Interfaces

Use interface Shape– Replace abstract class Shape

Interface– Declaration begins with interface keyword

– Classes implement an interface (and its methods)

– Contains public abstract methods Classes (that implement the interface) must implement

these methods

VTC Academy THSoft Co.,Ltd 37

1 // Fig. 10.18: Shape.java

2 // Shape interface declaration.

3

4 public interface Shape {

5 public double getArea(); // calculate area

6 public double getVolume(); // calculate volume

7 public String getName(); // return shape name

8

9 } // end interface Shape

Lines 5-7Classes that implement Shape must implement these methods

VTC Academy THSoft Co.,Ltd 38

1 // Fig. 10.19: Point.java

2 // Point class declaration implements interface Shape.

3

4 public class Point extends Object implements Shape {

5 private int x; // x part of coordinate pair

6 private int y; // y part of coordinate pair

7

8 // no-argument constructor; x and y default to 0

9 public Point()

10 {

11 // implicit call to Object constructor occurs here

12 }

13

14 // constructor

15 public Point( int xValue, int yValue )

16 {

17 // implicit call to Object constructor occurs here

18 x = xValue; // no need for validation

19 y = yValue; // no need for validation

20 }

21

22 // set x in coordinate pair

23 public void setX( int xValue )

24 {

25 x = xValue; // no need for validation

26 }

27

Error compile

VTC Academy THSoft Co.,Ltd 39

Action on class

Teacher – hauc2@yahoo.com– 0984380003– https://play.google.com/store/search?q=thsoft+co&c=apps

Captions Members

top related