You are never a loser until you quit trying!

Lập trình hướng đối tượng trong JAVA - Java's Object Oriented Programming

Chào các bạn đến với phanlamcoder.blogspot.com !

Contents
  • Khái niệm cơ bản trong lập trình hướng đối tượng (OOP)
  • Tính chất của OOP
  • OOP trong Java
  • Những câu hỏi hay gặp về OOP  trong Java

lap-trinh-huong-doi-tuong-trong-java




Khái niệm cơ bản trong lập trình hướng đối tượng (OOP)


Quay trở lại thời kỳ trước khi khai sinh lập trình hướng đối tượng, các ngôn ngữ đã sử dụng lập trình hướng thủ tục : 
    Chương trình = Cấu trúc dữ liệu(CTDL) + Giải thuật(GT)

Nếu CTDL thay đổi thì GT cũng phải thay đổi theo, các bài toán được chia làm các function => khó xây dựng chương trình lớn, khó nâng cấp, khó tái sử dụng, ...

Vì vậy cần phải tìm ra mô hình/hướng lập trình mới để đáp ứng các nhu cầu trên, đó là lý do OOP ra đời.

OOP là một triết lý thiết kế, hay còn gọi là một mô hình trong lập trình. OOP được áp dụng trong hầu hết các ngôn ngữ lập trình như C++, Java, C#, PHP, JS,  ...

Khái niệm:
Lập trình hướng đối tượng là một phương pháp để thiết kế một chương trình bởi sử dụng các lớp và các đối tượng. Nó làm đơn giản hóa việc duy trì và phát triển phần mềm, một số khái niệm cơ bản:

  • Đối tượng trong cụm từ "lập trình hướng đối tượng" nghĩa là một thực thể trong thế giới thực, chẳng hạn như bàn, quả bóng, con bò, …
  • Class là một template (mẫu) thể hiện các đặc tính và hành vi của đối tượng.
  • Object là một thể hiện của class (class là tập hợp các object).

Để hiểu rõ hơn về Class và Object các bạn có thể tham khảo ví dụ sau:

Bạn muốn đem đối tượng "xe" vào chương trình của bạn?

Đầu tiên bạn phải biết xe có những thuộc tính gì (màu xe, tốc độ cao nhất, ...) và nó có thể thực hiện chức năng gì (chạy, hú còi, blabla...) 
Từ đó xây dựng một class Xe khai báo thuộc tính(properties) và chức năng(method) bên trong class
Sau đó ta sử dụng class Xe để tạo ra instances (các thể hiện của đối tượng - hay còn gọi là object :)) ) bằng toán tử "new" : 

Xe xe1 = new Xe("đỏ", 500); // tạo ra xe1 có màu đỏ, tốc độ cao nhất 500km/h

xe1.chay(); // xe1 thực hiện chức năng quay bánh

Xe xe2 = new Xe("xanh", 200); //tạo ra xe2 có màu xanh, tốc độ cao nhất 200km/h

xe2.chay(); // xe2 chạy

xe2.hucoi() //xe2 hú còi

Tổng quát như sau

ClassName objectName = new className(params);
// parameter(tham số) có thể có hoặc không, chúng ta sẽ tìm hiểu sau.

  Như vậy từ 1 class ta có thể tạo vô số các object, hay nói cách khác class là khuôn mẫu để tạo ra các object.

Tính chất của OOP

OOP có 4 tính chất quan trọng đó là:

  • Tính kế thừa (inheritance): một đối tượng có thể có được các thuộc tính hoặc hành vi của đối tượng khác.
  • Tính đa hình (polymorphism): một tác vụ có thể được thực hiện theo nhiều cách khác nhau.
  • Tính trừu tượng (abstraction): ẩn chi tiết bên trong và hiển thị tính năng.
  • Tính đóng gói (encapsulation): gắn kết code và dữ liệu cùng với nhau vào trong một đơn vị unit đơn.
Các khái niệm trên có thể hơi khó hiểu, nhưng đừng hoang mang, hãy xem phần tiếp theo để có thể hiểu rõ hơn về 4 tính chất này.

OOP trong Java

- Tính kế thừa: tính chất này thể hiện qua việc một class có thể kế thừa một class khác bằng từ khóa extends (trong java không có đa kế thừa), một class có thể triển khai nhiều interface bằng từ khóa implements.
- Tính đa hình: một method có thể được thực hiện theo nhiều cách khác nhau bằng các phương thức overriding(ghi đè) và overloading(nạp chồng).
- Tính trừu tượng: việc định nghĩa một method nhưng không khai báo cách triển khai thông qua từ khóa abstract.
- Tính đóng gói: client chỉ sử dụng method mà mình được phép sử dụng mà không quan tâm đến cách mà method đó triển khai, nội dung của tính chất này đc thể hiện qua các phương thức getter & setter access modifier.

Các khái niệm, từ khóa quan trọng:
- Access modifier: dùng để giới hạn phạm vi truy cập của một thuộc tính, một method hoặc một class, nằm ở vị trí đầu tiên khi khai báo chúng. Nếu không chỉ rõ access modifier thì mặc định sẽ là Default.

oop-java-access-modifier
Class: lớp hiện tại, Package: lớp chung package với lớp hiện tại, Subclass: lớp con, Global: toàn cục

- Abstract
+ dùng để định nghĩa lớp hoặc method là abstract (thuần ảo) :
+ phương thức thuần ảo là phương thức không có khai báo cách triển khai (chỉ có vỏ, không có ruột :)) ).
+ lớp thuần ảo là lớp có thể chứa phương thức thuần ảo.
+ phương thức thuần ảo phải nằm trong một lớp thuần ảo, còn lớp thuần ảo có thể chứa hoặc không chứa phương thức thuần ảo.
+ chúng ta không thể tạo đối tượng bằng lớp thuần ảo.
- Interface
+ là một tập hợp các phương thức không được khai báo cách triển khai (giống như abstract method) và kết thúc bằng dấu chấm phẩy. (định nghĩa này còn được mở rộng trọng phiên bản java >7, các bạn có thể tìm hiểu ở bài học sau).
+ các class có thể implements interface và bắt buộc phải triển khai từng method trong nó.
+ trong interface có thể có thuộc tính nhưng đa phần thuộc tính đó đều là hằng số.
- Constructor
+ là phương thức đặc biệt có tên trùng với tên lớp và không có kiểu trả về.
+ phương thức khởi tạo đối tượng, khởi tạo các thuộc tính của đối tượng từ tham số bên ngoài hoặc tự khởi tạo mặc định.
- Overriding: lớp con ghi đè lên một phương thức của lớp cha hoặc của interface mà nó implements.
- Overloading: cho phép khai báo 2 hoặc nhiều phương thức cùng tên nhưng khác tham số truyền vào.
- Từ khóa quan trọng:
+ this: tham chiếu đến đối tượng của lớp hiện tại.
+ super: tham chiếu đến đối tượng lớp cha của lớp hiện tại.
+ static: chỉ định một thuộc tính, một method hay một khối lệnh là tĩnh, nghĩa là nó được khởi tạo/thực thi một lần duy nhất trong chương trình và được truy cập trực tiếp thông qua class mà không cần phải khởi tạo đối tượng. Mục đích để khai báo một tài nguyên dùng chung cho tất cả các đối tượng => giảm chi phí bộ nhớ.
+ final: dùng trong nhiều ngữ cảnh:
  •  thuộc tính: khi khai báo là hằng số (không thể thay đổi sau khi khai báo).
  •  method: khi không muốn method bị ghi đè.
  •  lớp: khi không muốn lớp bị kế thừa.

HTTP Requests

Vừa học kiến thức, vừa rèn luyện tiếng anh! Còn gì tuyệt vời hơn nữa 😊😊😋 
HTTP Requests

  1. HTTP Overview
  2. HTTP Parameters
  3. HTTP Messages
  4. HTTP Requests
  5. HTTP Responses
  6. HTTP Method
  7. HTTP Status Codes
  8. HTTP Header Fields
  9. HTTP Caching
  10. HTTP URL Encoding
  11. HTTP Security
  12. HTTP Message Examples
An HTTP client  sends an HTTP request to a server in the form of a request message which includes following format:

  • A Request-line
  • Zero or more header (General|Request|Entity) fields followed by CRLF
  • An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields
  • Optionally a message-body



The following sections explain each of entities used in an HTTP request message.

Request-Line

The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Let's discuss each of the parts mentioned in the Request-Line.

Request Method

The request method indicates the method to be perform on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The following table lists all the supported methods in HTTP/ 1.1




S.N. Method and Description
1 GET
The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
2 HEAD
Same as GET, but it transfers the status line and the header section only.
3 POST
A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.
4 PUT
Replaces all the current representation of the target resource with the uploaded content.
5 DELETE
Removes all the current representations of the target resource given by URI.
6 CONNECT
Establishes a tunnel to the server identified by a given URI.
7 OPTIONS
Describe the communication options for the target resource.
8 TRACE
Perform a message loop back test along with the path to the target resource.

Request-URI

The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. Following are the most commonly used forms to specify an URI:
Request-URI = "*" | absolutURI | abs_path | authority




S.N. Method and Description
1 The asterisk * is used when an HTTP request does not apply to a particular resource, but not the server itself, and is only allowed when the method used does not necessarily apply to a resource. For example:
OPTIONS * HTTP/1.1
2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is request to forward the request or service from a valid cache, and return the response. For example:
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1
3 The most common form of Request-URI is that used to identify a resource on an origin server or gateway. For example, a client wishing to retrieve a resource directly from the origin server would create a TCP connection to port 80 of the host "www.w3.org" and send the following lines:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org

Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root).

Request Header Fields

We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For now, let's check what Request header fields are.
 The request-header fields allow the client to pass additional information about the request, and about the client itself, to the server. These fields act as request modifiers. Here is a list of some important Request-header fields that can be used based on the requirement:

  • Accept-Charset
  • Accept-Encoding
  • Accept-Language
  • Authorization
  • Expect
  • From
  • Host
  • If-Match
  • If-Modified-Since
  • If-None-Match
  • If-Range
  • If-Unmodified-Since
  • Max-Forwards
  • Proxy-Authorization
  • Range
  • Referer
  • TE
  • User-Agent

You can introduce your custom fields in case you are going to write your own custom Client and Web Server.

Example of Request Message

Now let's put it all together to form an HTTP request to fetch hello.htm page from the web server running on tutorialspoint.com

GET /hello.htm HTTP/1.1

User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive


Here we are not sending any request data to the server because we are fetching a plain HTML page from the server. Connection is a general-header, and the rest of the headers are request headers. The following example shows how to send form data to the server using request message body:



POST /cgi-bin/process.cgi HTTP/1.1

User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
licenseID=string&content=string&/paramsXML=string


Here the given URL /cgi-bin/process.cgi will be used to process the passed data and accordingly, a response will be returned. Here content-type tells the server that the passed data is a simple web form data and length will be the actual length to the data put in the message body. The following example shows how you can pass plain XML to your web server:


POST /cgi-bin/process.cgi HTTP/1.1

User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: text/xml; charset=utf-8
Content-length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
<?xml version="1.0"  encoding="utf-8"?>
<string xmlns="http://clearforest.com/">string</string>

Tham khảo: Tutorialspoint.com 

HTTP Messages

HTTP Messages


  1. HTTP Overview
  2. HTTP Parameters
  3. HTTP Messages
  4. HTTP Requests
  5. HTTP Responses
  6. HTTP Method
  7. HTTP Status Codes
  8. HTTP Header Fields
  9. HTTP Caching
  10. HTTP URL Encoding
  11. HTTP Security
  12. HTTP Message Examples

    HTTP is based on the client-server architecture model and a stateless request/response protocol that operates by (điều hành bởi) exchanging messages across a reliable(xác thực/tin cậy) TCP/IP connection.

    An HTTP "client" is a program (Web browser or any other client) that establishes a connection to a server for the purpose of sending one or more HTTP request messages. An HTTP "server" is a program ( generally a web server like Apache Web Server or Internet Infomation Services IIS, etc. ) that accepts connections in order to serve HTTP request by sending HTTP response messages.

    HTTP make use of the Uniform Resource Identifier (URI) to identify a given resource and to establish a connection. Once the connection is established, HTTP messages are passed in a format similar to that used by the Internet mail [RFC3522] and the Multipurpose Internet Mail Extensions (MIME) [RFC2045]. These messages include requests from client to server and responses from server to client which will have the following format:

HTTP-message = <Request> | <Response> ; HTTP/1.1 messages

    HTTP requests and HTTP response use a generic message format consists of (bao gồm) the following four items.

  • A start-line
  • Zero or more header fields followed by CRLF
  • An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields
  • Optionally a message-body

    In the following sections, we will explain each of the entities used in an HTTP message.

Message Start-Line

     A start-line will have the following generic syntax:

start-line = Request-Line | Status-Line

  We will discuss Request-Line and Status-Line while discussing HTTP Request and HTTP Response messages respectively (một cách tương đối). For now, let's see the examples of start line in case of the request and response:

GET /hello.htm HTTP/1.1  (This is Request-Line sent by the client)

HTTP/1.1 200 OK               (This is Status-Line sent by the server)

Header Fields

    HTTP header fields provide required information about the request or response, or about the object sent in the message body. There are four types of HTTP message header:
  • General-header: These header fields have general applicability for both request and response messages.
  • Request-header: These header fields have applicability only for request messages.
  • Response-header: These header fields have applicability only for response messages.
  • Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request.
All the above mentioned headers follow the same generic format and each of the header fields consists of a name followed by a colon (:) and the fields value as follows:

message-header = field-name ":" [field-value]

Following are the examples of various header fields:

User-Agent: curl/7.16.3 OpenSSL/0.9.71 zlib/1.2.3
Host: www.example.com
Accept-Language: en, mi
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache
Last-Modified: Web, 22 Jul 2009 19:15:56 GMT
ETag: "34aa234-d-1568eb00"
Accept-Ranges: bytes
Content-Length: 51
Vary: Accept-Encoding
Content-Type: text/plain 

Message Body

    The message body part is optional for an HTTP message but if it is available, then it is used to carry the entity-body associated(liên kết) with the request or response. If entity body is associated, then usually Content-Type and Content-Length headers lines specify the nature of the body associated.

    A message body is the one which carries the actual HTTP request data (including from data and uploaded, etc.) and HTTP response data from the server (including files, images, etc.). Shown below is the simple content of a message body:

<html>
    <body>
                       <h1>Hello, World!</h1>
    </body>
</html>

Next two chapters will make use of above explained concepts to prepare HTTP Requests and HTTP Responses.


Tham khảo: https://www.tutorialspoint.com/

HTTP Parameters

HTTP Parameters

    
  1. HTTP Overview
  2. HTTP Parameters
  3. HTTP Messages
  4. HTTP Requests
  5. HTTP Responses
  6. HTTP Method
  7. HTTP Status Codes
  8. HTTP Header Fields
  9. HTTP Caching
  10. HTTP URL Encoding
  11. HTTP Security
  12. HTTP Message Examples

    This chapter is going to list down few of the important HTTP protocol parameters and their syntax the way they are used in the communication. For example, format for date, format for URL, etc. This will help you in constructing your request and response message while writing HTTP client or server programs. You will see the complete usage of these parameters subsequent chapters while learning the message structure for HTTP requests and responses.

HTTP Version

HTTP uses a <major>.<minor> numbering scheme to indicate version of the protocol. The version of an HTTP message is indicated by the HTTP-Version field in the first line. Here is the general syxtax of specifying HTTP version number:
HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
Example
HTTP/1.0 or HTTP/1.1

Uniform Resource Identifiers

Uniform Resource Identifiers (URI) are simply formatted, case-insensitive string containing name, location, ect. to identify a resource, for example, a website, a web service, etc. A general syntax of URI used for HTTP is as follows:
URI = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
Here if the port is empty or not given, port 80 is assumed for HTTP and an empty abs_path is equivalent to an abs_path of "/".The characters other than those in the reserved and unsafe sets are equivalent to their ""%" HEX HEX" encoding.
Example
The following three URIs are equivalent:
http://abc.com:80/~smith/home.html
http://ABC.com/%7Esmith/home.html
http://ABC.com:/%7esmith/home.html

Date/Time Formats

All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception. HTTP applications are allowed to use any of the following three representations of date/time stamps:
Sun,  06 Nov 1994 08:49:37 GMT   ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT  ; RFC 850, obsoleted by RFC 1036
Sun Nov    6 08:49:37 1994              ; ANSI C's asctime() format

Character Sets

We use character sets to specify the character sets that the client prefers. Multiple character sets can be listed separated by commas. If a value is not specified, the default is the US-ASCII.
Example
Following are the calid character sets:
US-ASCII or ISO-8859-1 or ISO-8859-7

Content Encodings

A content encoding value indicates that an encoding algorithm has been used to encode the content before passing it over the network. Content coding are primarily used to allow a document to be compressed or otherwise usefully transformed without losing the identity.
All content-encoding values are case-insensitive. HTTP/1.1 uses content encoding values in the Accept-Encoding and Content-Encoding header fields which we will see in the subsequent chapters.
Example
Following are the valid encoding schemes:
Accept-encoding: gzip or compress or deflate

Media Type

HTTP uses Internet Media Types in the Content-Type and Accept header fields in order to provide open and extensible data typing and type negotiation. All the Media-type values are registered with the Internet Assigned Number Authority (IANA). The general syntax to specify media type is as follows:
media-type   = type "/" subtype *(";" parameter )
The type, subtype, and parameter attribute names are case-insensitive.
Example
Accept: image/gif

Language Tags


HTTP uses language tags within the Accept-language and Content-Language fields. A language tag is composed of one or more parts: a primary language tag and a possibly empty series of subtags:
language-tag = primary-tag *("-" subtag )
White spaces are not allowed within the tag and all tags are case-insensitive.
Example
Example tags include:
en, en-US, en-cockney, i-cherokee, x-pig-latin
where any two-letter primary-tag is an ISO-639 language abbreviation and any two-letter initial subtag is an ISO-3166 contry code.


Tham khảo: https://www.tutorialspoint.com/ 

HTTP Overview

Vừa học kiến thức, vừa rèn luyện tiếng anh! Còn gì tuyệt vời hơn nữa 😊😊😋 
  1. HTTP Overview
  2. HTTP Parameters
  3. HTTP Messages
  4. HTTP Requests
  5. HTTP Responses
  6. HTTP Method
  7. HTTP Status Codes
  8. HTTP Header Fields
  9. HTTP Caching
  10. HTTP URL Encoding
  11. HTTP Security
  12. HTTP Message Examples


    The HyperText Transfer Protocol (HTTP) is an application-level protocol for distributed (phân phối), collaborative (cộng tác), hyper-media information systems. This is the foundation for data communication for World Wide Web (i.e. internet) since 1990. HTTP is a generic and stateless (phi trạng thái) protocol which can be used for other purposes as well using extensions of its request methods, error codes and headers.
    Basically, HTTP is a TCP/IP based communicate protocol, that used to deliver (phân phối) data (HTML files, image files, query results, ect.) on the WWW. The default port is TCP 80, but other ports can be used as well. It provides a standardized way for computers to communicate with each other. HTTP specification specifies how clients' data will be constructed and send to the server, and how to the servers response  these requests.

Basic features:

   There are three features that make HTTP a simple but powerful protocol:



  • HTTP is a connectionless (kết nối không liên tục): The HTTP client, i.e., a browser initiates an HTTP request and after a request is made,  the client disconnects from the server and waits for a response. The server processes the request and re-establishes  (thiết lập lại) the connection with the client to send a response back. 
  • HTTP is media independent (phương tiện độc lập): It means, any type of data can be sent by HTTP as long as both the client and the server know how to handle the data content. It's required for the client as well as the server specify the content type using appropriate (thích hợp) MIME-type.
  • HTTP is a stateless: As mentioned above, HTTP is connectionless and it's a direct result HTTP being a stateless protocol. The client and the server are aware of each other during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the server can retain (ghi nhớ) information between different requests across the web pages.
Note: HTTP/1.0 uses a new connection for each request/response exchange (trao đổi) where as HTTP/1.1 may be used for one or more request/response exchanges.

Basic Architecture:

    The following diagram shows a basic architecture of a web application and depicts (miêu tả) where HTTP sits:

HTTP Architecture

    The HTTP is a request/response protocol based on the client/server based architecture where web browsers, robots, search engines,  ect., act like HTTP clients and the Web server acts like servers.

Client

    The HTTP client sends  a request to the server in the form of a request method, URI, and protocol version followed by a MIME-like message containing the request modifiers, client information, and possible body content over a TCP/IP connection.

Server

    The HTTP server responds with a status line, including the message's protocol version and a success or error code followed by a MIME-like message containing server information, entity meta information , and possible entity-body content.

Tham khảo: tutorialspoint.com