JHTP小结_第三章_类、对象、方法及字符串简介

来源:互联网 发布:数据完整性保护 编辑:程序博客网 时间:2024/06/13 05:28

 

Summary

Section 3.2 Instance Variables,setMethods andgetMethods

Each class you create becomes a new type that can be used to declare variablesand create objects.

Youcan declare new classes as needed; this is one reason Java is known as anextensible language.

Section 3.2.1Account Class with an Instance Variable, asetMethod and agetMethod

Each class declaration that begins with the access modifier (p. 71)publicmustbe stored in a filethat has the same name as the class and ends with the.javafilenameextension.

Every class declaration contains keywordclass followedimmediately by the class’s name.

Class, method and variable names are identifiers. By convention all use camelcase names. Classnames begin with an uppercase letter, and method andvariable names begin with a lowercase

letter.

Anobject has attributes that are implemented as instance variables (p. 72) andcarried with it throughout its lifetime.

Instance variables exist before methods are called on an object, while themethods are executing and after the methods complete execution.

Aclass normally contains one or more methods that manipulate the instancevariables that belong

to particular objects of the class.

Instance variables are declared inside a class declaration but outside the bodiesof the class’s method

declarations.

Each object (instance) of the class has its own copy of each of the class’sinstance variables.

Most instance-variable declarations are preceded with the keywordprivate(p.72), which is an access modifier. Variables or methods declared with accessmodifierprivate are accessible only to methods of the classin which they’re declared.

Parameters are declared in a comma-separated parameter list (p. 73), which islocated inside theparentheses that follow the method name in the methoddeclaration. Multiple parameters are

separated by commas. Each parameter must specify a typefollowed by a variable name.

Variables declared in the body of a particular method are local variables andcan be used only inthat method. When a method terminates, the values of itslocal variables are lost. A method’s parametersare local variables of the method.

Every method’s body is delimited by left and right braces ({and}).

Each method’s body contains one or more statements that perform the method’stask(s).

Themethod’s return type specifies the type of data returned to a method’s caller.Keywordvoid indicates that a method will perform a task but will notreturn any information.

Empty parentheses following a method name indicate that the method does notrequire any parametersto perform its task.

When a method that specifies a return type (p. 73) other thanvoidiscalled and completes itstask, the method must return a result to its callingmethod.

Thereturnstatement(p. 74) passes a value from a called method back to its caller.

Classes often providepublic methods to allow theclass’s clients toset orget privateinstancevariables. The names of these methods need not begin withsetor get,but this naming convention

is recommended.

Section 3.2.2AccountTest Class That Creates and Uses an Object ofClassAccount

Aclass that creates an object of another class, then calls the object’s methods,is a driver class.

ScannermethodnextLine(p.75) reads characters until a newline character is encountered, then returns the characters as aString.

Scannermethodnext(p.75) reads characters until any white-space character is encountered, then returns the characters as aString.

Aclass instance creation expression (p. 75) begins with keywordnewandcreates a new object.

Aconstructor is similar to a method but is called implicitly by thenewoperatorto initialize anobject’s instance variables at the time the object iscreated.

Tocall a method of an object, follow the object name with a dot separator (p.76), the methodname and a set of parentheses containing the method’sarguments.

Local variables are not automatically initialized. Every instance variable hasa default initial value—a value provided by Java when you do not specify theinstance variable’s initial value.

Thedefault value for an instance variable of typeString is null.

Amethod call supplies values—known as arguments—for each of the method’sparameters. Eachargument’s value is assigned to the correspondingparameter in the method header.

Thenumber of arguments in a method call must match the number of parameters in themethoddeclaration’s parameter list.

Theargument types in the method call must be consistent with the types of thecorrespondingparameters in the method’s declaration.

Section 3.2.3 Compiling and Executing anApp with Multiple Classes

Thejavaccommandcan compile multiple classes at once. Simply list the source-code filenames after the command with each filename separated by a spacefrom the next. If the directory containingthe app includes only one app’s files, you can compileall of its classes with the commandjavac *.java. The asterisk (*) in*.javaindicatesthat all files in the current directory ending with the filename extension “.java”should be compiled.

Section 3.2.4Account UML Class Diagram with an Instance Variableandset and

getMethods

Inthe UML, each class is modeled in a class diagram (p. 77) as a rectangle withthree compartments.The top one contains the class’s name centeredhorizontally in boldface. The middle one

contains the class’s attributes, which correspond toinstance variables in Java. The bottom onecontains the class’s operations (p. 78), which correspondto methods and constructors in Java.

TheUML represents instance variables as an attribute name, followed by a colon andthe type.

Private attributes are preceded by a minus sign () in the UML.

TheUML models operations by listing the operation name followed by a set ofparentheses. Aplus sign (+) in front of the operation name indicatesthat the operation is a public one in the

UML (i.e., apublic method in Java).

TheUML models a parameter of an operation by listing the parameter name, followedby a colonand the parameter type between the parentheses after theoperation name.

TheUML indicates an operation’s return type by placing a colon and the return typeafter theparentheses following the operation name.

UMLclass diagrams do not specify return types for operations that do not returnvalues.

Declaring instance variablesprivate is known as data hidingor information hiding.

Section 3.2.5 Additional Notes on ClassAccountTest

Youmust call most methods other thanmain explicitly to tell themto perform their tasks.

Akey part of enabling the JVM to locate and call methodmain tobegin the app’s execution isthe static keyword, which indicatesthatmain is a static methodthat can be called without first

creating an object of the class in which the method isdeclared.

Most classes you’ll use in Java programs must be imported explicitly. There’s aspecial relationshipbetween classes that are compiled in the same directory.By default, such classes are consideredto be in the same package—known as the default package.Classes in the same package areimplicitly imported into the source-code files of otherclasses in that package. Animport declarationis not required when one class in a package uses anotherin the same package.

Animportdeclarationis not required if you always refer to a class with its fully qualified classname, which includes its package name and class name.

Section 3.2.6 Software Engineering withprivate Instance Variables andpublic set

andget Methods

Declaring instance variablesprivate is known as data hidingor information hiding.

Section 3.3 Primitive Types vs. ReferenceTypes

Types in Java are divided into two categories—primitive types and referencetypes. The primitivetypes areboolean,byte,char,short,int,long,floatanddouble. All other types arereference

types, so classes, which specify the types of objects,are reference types.

Aprimitive-type variable can store exactly one value of its declared type at atime.

Primitive-type instance variables are initialized by default. Variables oftypesbyte, char, shortint,long, floatand doubleareinitialized to0. Variables of typebooleanareinitialized tofalse.

Reference-type variables (called references; p. 81) store the location of anobject in the computer’smemory. Such variables refer to objects in the program.The object that’s referenced may

contain many instance variables and methods.

Reference-type instance variables are initialized by default to the valuenull.

Areference to an object (p. 81) is required to invoke an object’s methods. Aprimitive-type variabledoes not refer to an object and therefore cannot be usedto invoke a method.

Section 3.4Account Class: Initializing Objects withConstructors

Each class you declare can optionally provide a constructor with parametersthat can be used toinitialize an object of a class when the object iscreated.

Java requires a constructor call for every object that’s created.

Constructors can specify parameters but not return types.

Ifa class does not define constructors, the compiler provides a defaultconstructor (p. 83) with

no parameters, and the class’s instance variables areinitialized to their default values.

Ifyou declare a constructor for a class, the compiler willnot createadefault constructor for thatclass.

TheUML models constructors in the third compartment of a class diagram. Todistinguish a

constructor from a class’s operations, the UML places theword “constructor” between guillemets(<< and >>; p. 84) before the constructor’s name.

Section 3.5Account Class with a Balance; Floating-PointNumbers and Typedouble

Afloating-point number (p. 84) is a number with a decimal point. Java providestwo primitivetypes for storing floating-point numbers in memory—floatanddouble(p.84).

Variables of typefloat represent single-precision floating-pointnumbers and have seven significant

digits. Variables of typedouble representdouble-precision floating-point numbers. Theserequire twice as much memory asfloat variablesand provide 15 significant digits—approximatelydouble the precision offloat variables.

Floating-point literals (p. 84) are of typedouble bydefault.

ScannermethodnextDouble(p.88) returns a double value.

Theformat specifier%f (p. 88) is used to output values of typefloator double.The format specifier

%.2fspecifies that two digits of precision (p.88) should be output to the right of the decimalpoint in the floating-point number.

Thedefault value for an instance variable of typedouble is 0.0,and the default value for an instancevariable of typeint is 0.

 

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机上的短信图标没了怎么办 qq密保手机被别人换了怎么办 苹果六手机很卡网络不给力怎么办 堡垒之夜卡在载入界面怎么办 登录新福建一直说网络不给力怎么办 开发游戏平台给了钱不给东西怎么办 代号英雄与服务器断开连接了怎么办 千牛聊天页面买家信息不显示怎么办 秒拍存草稿箱的视频没了怎么办? 登录山东掌厅出现服务器错误怎么办 微信号被多人投诉被限制登录怎么办 联想平板电脑开机密码忘记了怎么办 申请的qq没登录忘了账号怎么办 炫舞时代由于网络原因登不上怎么办 qq申请太多进不了热聊怎么办 手机号申请的微信号被盗了怎么办 买菜别人少找了钱不还怎么办 在掌上英雄联盟买皮肤买错区怎么办 win8我的电脑图标没了怎么办 英雄联盟老是卡在安全扫描怎么办 英雄联盟活动送皮肤没送怎么办 电脑换完系统有些页面打不开怎么办 王卡助手交手机费页面打不开怎么办 在浏览器上打不开路由器页面怎么办 英雄联盟读条的时候自动关机怎么办 手机的位置信息开不了怎么办呢 滴滴车主接到乘客返回路程要怎么办 移动换话费积分是发什么短信怎么办 手机店积分换手机被贷款怎么办 心悦俱乐部礼包已过期是怎么办 心悦兑换的东西不是账号绑定怎么办 心悦会员绑定的手机号不用了怎么办 想在京东商城开个网店怎么办呢 京东买了东西收货了不想要了怎么办 京东转卖的商品有问题怎么办 如果衣服下架了然后有退货怎么办 想买二手车可没有懂车的人怎么办 买车的时候异地车牌回家怎么办 天猫下单显示下单人数太多券怎么办 英雄联盟进入游戏后无限崩溃怎么办 打开电视显示百度影棒打不开怎么办