"Introduction to Programming (JAVA) • Category 1.2"

Source: Internet
Author: User
Tags gcd greatest common divisor

This section provides a preliminary introduction to the details of the class.

1.2.1 Structure of the class body

First of all, according to my object priority teaching Strategy , first introduce the knowledge of the class rather than the first control structure. So, as early as the second section of the first chapter, we give a complete example of dog routines 1-1. The 1.2.1 class body structure surrounds the routines, describing the state, behavior, and Identity (reference) in general. Many things, inconvenient to explain now, do not explain. The students first operate it in the BlueJ .

★learning by doing.

Package zoo;/** * Class dog describes the human faithful friend dog. class declaration. * @author yqj2065  * @ Version 0.1 */public class Dog {  //class header, class declaration    private String name = "Baby";//String dog name, default call B Aby Private indicates the access rights of the privately owned    boolean sex;  Boolean/Logical Data gender. There are only two sexes, one must live. True represents the male.    private int age = 0;    The integer age, which defaults to 0 years. /*        setter    and getter*//**     * Set the name of the dog.     * @param n Dog's name (string).     * @throws later to consider the parameter check things, now can not be confused. The president's name must not be used.     *    /public void SetName (String n) {        name = n;    } Set the dog's name. Void indicates that the return value is empty and not required.    String  getName () {return name;}//return/returns the name of the dog      /** @param  ismale  true for male */    void   Setsex (Boolean ismale) {  sex = ismale;}    int    getage () {return age;}        /** Wag the tail behavior. Output string Hello World *    /Void Wagtail ()  {  System.out.println ("Hello World");     }    /** Dog will do simple addition *    /int Add (int i, int j) {return i+j;}    }

1. The state of an object is a collection of all property values for the object. Each object has its own memory space to save its own state, that is, the name, age, gender, and so on attribute values.

2. The "act" of an objective object is a generalization. If a dog has a wagging tail, a roaring action, an activity that sets his age or asks his age, an abstract object, such as a circle, has a formula, calculation procedure, or algorithm for calculating its area and perimeter. The source code models the object behavior as executable blocks of code, called methods in Java, and methods for reading and writing to an attribute, commonly known as setter and getter.

3. The identity (or identity) of the object, in the scope of this tutorial, is judged entirely in terms of where it occupies in memory (by reference) . That is, two objects occupy the same memory location, they are "the same" object; otherwise, even if their state is exactly the same, they are simply "equal".


Exercise 1-11. Use the BlueJ IDE to master the contents of the Appendix A.1: Edit and compile the source code.

Exercise 1-12: Mastering the Appendix A.2 interacting with Classes and objects: Create a Dog object in BlueJ and call its Wagtail (), GetName (), and SetName (String) methods. Describes how to view the effects of the previous 3 method calls. Reminder: Use double quotation marks to enclose a string literal as a parameter.

Exercise 1-17: What is the identity of an object?


4. Overview of the structure of classes

Class as the template for an object, the most basic component is the state and behavior of the object, including the inner class, the internal interface (see [9.4 Nested types]). In Java, they are called members of the class .

Class also has an important job to prepare for making your own objects easier to create. Thus in the class definition, the source code is often placed in the code block of this purpose--constructors, initialization blocks。 These code blocks are not used to describe object characteristics, so they are not considered members of the class. Just like auditors, although in class, it is not a part of the class. Sometimes called it a non-member of the class

Therefore, the structure of the ordinary class is usually:

Package Xxx;//import xxx;/** Class Introduction */public class xxxx{    < domain declaration >    < constructor, initialization block >    < method definition >    < internal class, internal interface;}
1.2.2 Blanks and annotations

The following is a 1-1 zoo around the routine. Dog.java, which describes the composition of the source code-- comments, whitespace , and five Java lexical elements : identifiers, keywords, literals, operators, and separators. Please also make a game to copy the dog code to the zoo. Dog4fun, remove the sections that have been introduced.

Whitespace includes spaces, tabs (tab), and line breaks.

* Between words and words such as private String name, you need to use a space to interval (it is a delimiter)

* Tab-Regular indentation, the main function is to make the code structure clear.

* Source code is a plain text file, each line ends with a newline character. The newline character has a CR in ASCII code (carriage return, ' \ R ', 0x0D, 13) and LF (line feed, ' \ n ', 0x0A, 10). (When reading a file, be aware of the line break processing.) )

Note that the book occupies a space close to "the structure of the class", in particular the enumeration of commonly used Javadoc block tags. No matter how much we emphasize,

★ The program must be written for people to read, only occasionally let the machine perform--abelson and Sussman

★any fool can write code that a computer can understand. Good programmers write code that humans can understand--martin Fowler

1.2.35 Types of Java elements

Java lexical elements (tokens, language symbols) are the smallest units that the Java compiler can recognize, including the following five types: identifiers, keywords, literals, operators, and separators .

Routines 1-2 different kinds of identifiers are independent of each other

Package Semantics;public class Yqj {   yqj yqj (yqj yqj) {     yqj: for        (;;) {          if (yqj. YQJ (YQJ) ==yqj) break             yqj;     return YQJ;}   }
The syntax for identifiers is simply enumerated. In Java. identifiers, comments, character literals, string literals can use Unicode, while other Java elements, such as keywords, operators, and so on, use ASCII characters.

Exercise 1-25. Defines a method that determines whether a character is an identifier-free character. Replace the symbol "★" in the following code with a variety of characters, including kanji. and confirms that 2mail, room# is or is not a valid identifier.

chard= ' ★ ';

Booleanb1=character.isjavaidentifierstart (d);//is a valid identifier first character

Booleanb2=character.isjavaidentifierpart (d);

SYSTEM.OUT.PRINTLN (B1 + "" + B2);

The details of the available characters refer to the documentation for methods such as Character.isjavaidentifierstart () in JDK documentation.

(This is my attempt, at this stage, can students complete exercise 1-25?) )

Exercise 1-30. The ASCII of the value 0, the letter A, a, respectively, is ____. (1) 0, 65, 66 (2) 48, 65, 97 (2) 48, 96, 97.

2. Keywords

Abstract

Assert

Boolean

Break

Byte

Case

Catch

Char

Class

Const

Continue

Default

Do

Double

Else

Enum

Extends

Final

Finally

Float

For

Goto

If

Implements

Import

instanceof

Int

Interface

Long

Native

New

Package

Private

Protected

Public

Return

Short

Static

Strictfp

Super

Switch

Synchronized

This

Throw

Throws

Transient

Try

void

Volatile

While

False, True, and null are theoretically literal and are not populated in table 1-1.

3. Text

Text is also known as a constant value, a literal value.

Integer literals usually use decimal numbers, or 2, 8, or 16 digits, and numbers can be added to enhance readability, with 0 (0) being octal, and numbers starting with 0 B (0b or 0B) being binary numbers, and numbers starting with 0 x (0x or 0X) are hexadecimal digits. The string literal is a reference to a string object.

The 4.[3.2.2 operator] will fully describe the operator.

5. Separators (separators) separate the different parts of the program. such as a space split word, comma split method parameters, semicolon represents the end of the statement (because multiple statements can be placed on one line). The rest is {} ().

Exercise 1-35: Write the program TypeSystem.primitive.Literal.java and verify the syntax of the various words. (I find I have a tendency to be extremely dismissive of grammar teaching.) )

1.2.4 syntax, semantics and conventions Grammar (syntax, syntax; syntactic grammar, grammatical rules)A series of lexical elements are strictly defined to form a syntactic correct statement. It is when you write a programmust followThe rules. The compiler is able to determine whether many elements of a program are correctly grouped by token and a set of grammatical rules in the programming language.

For new programmers, grammatical errors are very easy to come by.

Semantics (or semantics, semantics) usually refer to the meaning expressed by the language structure, or what the computer will do when a statement executes. In the vast majority of cases, high-level languages use natural language and mathematical idioms to express their semantics, so they can be less concerned with semantics, often combining grammar and semantics into one. The more language structures you can understand with intuition , the more friendly the language is.

The semantics of language structures are usually clear, that is, each statement has only one interpretation. However, sometimes a language does not define its semantics for a structure, such as the Order of evaluation of expressions in the [3.2.2 Operator], and does not define its semantics in the C language. With a legitimate statement, different programmers may express different meanings, and the results of different execution environments may be different. In addition, the language structure is different from what people take for granted , it is necessary to pay attention to the semantic learning. Such as

for (int x:list) {

x + +;

}

Don't expect it to add one to the elements of int[]list = {1,3,5,7,9}, making the array element {2,4,6,8,10}.


Convention (Convention). The syntax is a requirement that programmers "must" obey, otherwise the compilation does not pass. The convention is "should" be adhered to, because it is the programmer community requirements. The agreement is like the social morality restraint in the real life--should give seats to the elderly and pregnant women. The basic reason for a contract is to make it easy for programmers to read (others ') code. Programming conventions can effectively enhance the readability of code, better maintenance. such as naming conventions, typographic conventions, and so on.

1.2.5 Case: Score

Programs are not all examples of language teaching such as dog, first look at some practical and simple code.

The fraction class only lists the addition function, other function code such as subtraction, multiplication after completion of the [3.2 implementation], please implement it yourself . In order to get the normalized form of fractions, a function module gcd (int,int), which calculates the greatest common divisor of A/b, is implemented using Euclidean (Euclid) algorithm/Euclidean method, see [10.1.1 algorithm].

Package Tips;public class fraction{private int num;//molecule numerator private int den = 1;//denominator denominator pub LIC int Getnum () {return num;}    public int Getden () {return den;}    Public fraction () {this (0);}    /** N/1 form of the score */public fraction (int N) {num = N; }/** creates a fraction equal to n/d * @param N numerator numerator, * @param D denominator denominator, not 0 int value. */Public fraction (int n, int D) {int n = n >= 0?        N:-N; int d = d >= 0?        D:-D; int g = GCD (n, D); Normalized this.num = ((n>= 0) = = (d>= 0))?        (n/g):(-n/g);    This.den = d/g;         }/** adds a fraction to this object body */public void Add (fraction f) {num= Num*f.den +den*f.num;         Den = den *f.den;         int g = GCD (Num,den);         Num/= g;    Den/= g;            }/** calculates the greatest common divisor of a, B greatest common divisor */public final int gcd (int a,int b) {while (b! = 0) {            int tep=a% B;            A = b;        b = tep; } return a>=0?a:-a; /** Overwrite object's tostring () */@Override public String ToString () {return (Den = = 1)?    ("" +getnum ()):(getnum () + "/" +getden ()); } }

This section A total of 10 pages, recommended teaching class 1h, self-taught 4h--to do exercise-oriented.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Introduction to Programming (JAVA) • Category 1.2"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.