Introduction to Java---Basic Grammar & Basic Common Sense & Coding Standards & Naming Standards

    A Java program can be thought of as a collection of objects that work together by calling each other's methods. The following briefly introduces the concepts of classes, objects, methods, and instance variables.

 

  • Object : An object is an instance of a class that has state and behavior. For example, a dog is an object whose states are: color, name, breed; behaviors are: tail wagging, barking, eating, etc.
  • Class : A class is a template that describes the behavior and state of a class of objects.
  • Methods : Methods are behaviors, and a class can have many methods. Logical operations, data modification, and all actions are done in methods.
  • Instance Variables : Each object has unique instance variables, and the state of the object is determined by the values ​​of these instance variables.

    When writing Java programs, you should pay attention to the following points:

 

  • Case Sensitivity : Java is case sensitive, which means that the identifiers Hello and hello are different.
  • Class names : For all classes, the first letter of the class name should be capitalized. If the class name consists of several words, the first letter of each word should be capitalized, such as MyFirstJavaClass .
  • Method names : All method names should start with a lowercase letter. If the method name contains several words, capitalize the first letter of each subsequent word.
  • Source file name : The source file name must be the same as the class name. When saving the file, you should use the class name as the filename (remember that Java is case sensitive), and the filename extension should be .java. (If the filename and classname are not the same it will cause a compile error).
  • Main method entry : All Java programs are executed by the public static void main(String []args) method.

    All Java components require names. Class names, variable names, and method names are all called identifiers. There are a few things to note about Java identifiers:

 

  • All identifiers should start with a letter (AZ or az), dollar sign ($), or underscore (_)
  • The first character can be followed by any combination of letters (AZ or az), dollar signs ($), underscores (_) or numbers
  • Keywords cannot be used as identifiers
  • Identifiers are case sensitive
  • Examples of legal identifiers: age, $salary, _value, __1_value
  • Examples of illegal identifiers: 123abc, -salary

    Like other languages, Java can use modifiers to modify methods and properties in a class. There are two main types of modifiers:

 

  • Access control modifiers: default, public , protected, private
  • Non-Access Control Modifiers: final, abstract, strictfp

    There are mainly the following types of variables in Java:

 

  • local variable
  • Class variables (static variables)
  • member variables (non-static variables)

    Arrays are objects stored on the heap and can hold multiple variables of the same type. In later chapters, we will learn how to declare, construct and initialize an array.

    Java 5.0 introduced enumerations, which restrict variables to pre-set values. Using enums can reduce bugs in your code. For example, let's design a program for a juice store that will limit juice to small, medium, and large. That means it doesn't allow customers to order juices other than these three sizes:

 

class FreshJuice {
    enum FreshJuiceSize{ SMALL, MEDIUM , LARGE }
    FreshJuiceSize size; } public class FreshJuiceTest {     public static void main(String []args){         FreshJuice juice = new FreshJuice();         juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;     } }  

    The thing to note here is that enumerations can be declared individually or inside a class. Methods, variables, and constructors can also be defined in enumerations.

    The Java keywords are listed below. These reserved words cannot be used in the names of constants, variables, and any identifiers:

 

category keywords illustrate
Access control private private
protected under protection
public public
Class, method, and variable modifiers abstract declarative abstraction
class kind
extends extend, inherit
final final value, immutable
implements implement (interface)
interface interface
native native, native method (non-Java implementation)
new new, create
static static
strictfp strict, precise
synchronized thread, synchronization
transient short
volatile Volatile
program control statement break out of the loop
case define a value for switch to choose from
continue continue
default default
do run
else otherwise
for cycle
if if
instanceof example
return return
switch Select execution based on value
while cycle
error handling assert Assert whether an expression is true
catch catch exception
finally Execute with or without exception
throw throws an exception object
throws declares that an exception may be thrown
try catch exception
package related import introduce
package Bag
basic type boolean boolean
byte byte type
char character type
double double precision floating point
float single precision floating point
int Integer
long long integer
short short integer
null null
variable reference super superclass
this this class
void no return value
reserved keywords goto is a keyword, but cannot be used
const is a keyword, but cannot be used

    Similar to C/C++, Java also supports single-line and multi-line comments. Characters in comments will be ignored by the Java compiler:

 

public class HelloWorld {
 /* this is the first Java program  * it will print Hello World * this is an example of a multi-line comment */     public static void main(String []args){ // this is an example of a single line comment / * This is also an example of a single line comment */         System.out.println( "Hello World" );     } }     

    Blank lines, or lines with comments, are ignored by the Java compiler.

    In Java, a class can be derived from other classes. If you are creating a class, and a class already exists with the properties or methods you need, you can extend the newly created class from that class. With inherited methods, methods and properties of existing classes can be reused without rewriting the code. Inherited classes are called superclasses, and derived classes are called subclasses.

    在Java中,接口可理解为对象间相互通信的协议。接口在继承中扮演着很重要的角色。接口只定义派生要用到的方法,但是方法的具体实现完全取决于派生类。

    下面我们来看下Java 源程序与编译型运行区别:


    我们还要注意,标识符可以用来标识变量名、类名、类中的方法名和文件名等。来看下命名规则:

 

  • (1) 由字母、数字、下划线、$组成,不能以数字开头。
  • (2) 大小写敏感。
  • (3) 不得使用java中的关键字和保留字。

    关键字:都是小写的,jdk1.2多了strictfp(经准浮点型),关键字 jdk1.4多了assert(断言)关键字,jdk1.5多了enum(枚举) 关键字。true、false、null 严格说不应该算关键字,应称其为保留字更合适。

    下面有几个常用的编码习惯:

 

  • (1) 标识符要符合语义信息。
  • (2) 包名所有字母小写。
  • (3) 类名每个单词首字母大写,其它小写,如:TarenaStudent。
  • (4) 变量和方法:第一个单词小写,从第二个单词开始首字母大写,如:tarenaStudent。
  • (5) 常量:所有字母大写,每个单词之间用 _ 连接。

    再来看下常用的几个转义字符:

 

"\b" (退格)
"\f" (换页) "\n" (换行) "\r" (回车) "\t" (水平制表符(到下一个tab位置)) "\' " (单引号) "\" " (双引号) "\\" (反斜杠)

    Java的八种基本类型:(按字节来分)

 

boolean   布尔型   1个字节 8bit(8位)

byte     字节类型   1个字节

char     字符类型   2个字节

short     短整型     2个字节

int          整型        4个字节

float      浮点型(单精度)4个字节

long      长整型      8个字节

double   双精度类型  8个字节

    Java中默认的整数类型是int,如果要定义为long ,则要在数值后加上L或者l。默认的浮点型是双精度浮点,如果要定义float,则要在数值后面加上f或者F。一个字节等于8位,1个字节等于256个数。2^8。一个英文字母或者阿拉伯数字占一个字节。一个汉字占2个字节。

    还有一些命名规范大家参考下:

 

1、 项目名全部小写

2、 包名全部小写

3、 类名首字母大写,如果类名由多个单词组成,每个单词的首字母都要大写。如:public class MyFirstClass{}

4、 变量名、方法名首字母小写,如果名称由多个单词组成,每个单词的首字母都要大写。如:

int index=0; public void toString(){}

5、 常量名全部大写

public static final String GAME_COLOR="RED";

6、所有命名规则必须遵循以下规则:

  • 1)、名称只能由字母、数字、下划线、$符号组成
  • 2)、不能以数字开头
  • 3)、名称不能使用JAVA中的关键字。
  • 4)、坚决不允许出现中文及拼音命名。

    再来看一些注释规范:

    首先是类注释,在每个类前面必须加上类注释,注释模板如下:

 

/**
* Copyright (C), 2006-2010, ChengDu Lovo info. Co., Ltd.
* FileName: Test.java
* 类的详细说明
*
* @author 类创建者姓名
* @Date    创建日期
* @version 1.00
*/

    再来是属性注释,在每个属性前面必须加上属性注释,注释模板如下

 

/** 提示信息 */
private String strMsg = null;

    然后是方法注释,在每个方法前面必须加上方法注释,注释模板如下:

 

/**
* 类方法的详细使用说明
*
* @param 参数1 参数1的使用说明
* @return 返回结果的说明
* @throws 异常类型.错误代码 注明从此类方法中抛出异常的说明
*/

    还有就是构造方法注释,在每个构造方法前面必须加上注释,注释模板如下:

 

/**
* 构造方法的详细使用说明
*
* @param 参数1 参数1的使用说明
* @throws 异常类型.错误代码 注明从此类方法中抛出异常的说明
*/

    还有方法内部注释,在方法内部使用单行或者多行注释,该注释根据实际情况添加:

 

//背景颜色
Color bgColor = Color.RED

    再来看下编程规范:

 

package的命名: package 的名字由全部小写的字母组成,例如:com.runoob。

class和interface的命名: class和interface的名字由大写字母开头而其他字母都小写的单词组成,例如:Person,RuntimeException。

class变量的命名: 变量的名字用一个小写字母开头,后面的单词用大写字母开头,例如:index,currentImage。

class 方法的命名: 方法的名字用一个小写字母开头,后面的单词用大写字母开头,例如:run(),getBalance()。

staticfinal变量的命名: static final变量的名字所有字母都大写,并且能表示完整含义。例如:PI,PASSWORD。

参数的命名: 参数的名字和变量的命名规范一致。

数组的命名: 数组应该总是用这样的方式来命名:byte[] buffer。

    最后再来看下,一个完整的Java。源程序应该包括下列部分

 

  •  package”语句,该部分至多只有一句,必须放在源程序的第一句。
  •  import语句,该部分可以有若干import语句或者没有,必须放在所有的类定义之前。
  •  public classDefinition,公共类定义部分,至多只有一个公共类的定义,Java语言规定该Java源程序的文件名必须与该公共类名完全一致。
  •  classDefinition,类定义部分,可以有0个或者多个类定义。
  • interfaceDefinition,接口定义部分,可以有0个或者多个接口定义。

    package语句:由于Java编译器为每个类生成一个字节码文件,且文件名与类名相厅因此同名的类有可能发生冲突。为了解决这一问题,Java提供包来管理类名空间,包实 提供了一种命名机制和可见性限制机制。

    下面是一个小例子:

 

package javawork.helloworld; /*把编译生成的所有.class文件放到包javawork.helloworld中*/ import java awt.*; //告诉编译器本程序中用到系统的AWT包 import javawork.newcentury; /*告诉编译器本程序中用到用户自定义的包javawork.newcentury*/ public class HelloWorldApp{...} /*公共类HelloWorldApp的定义,名字与文件名相同*/ class TheFirstClass{...}; //第一个普通类TheFirstClass的定义  interface TheFirstInterface{......} /*定义一个接口TheFirstInterface*/

    好啦,这次的分享就到这里了。这次主要是分享下java编程时需要注意的地方,都是些小常识。如果感觉不错的话,请多多点赞支持哦。。。

  原文链接:https://blog.csdn.net/luyaran/article/details/80092488

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324916004&siteId=291194637