目录

    --- 修饰符

    --- 运算符

    --- 循环结构

    --- 分支结构

修饰符:

 修饰符用来定义类、方法或者变量,通常放在语句的最前端。如下:

public class className {
   // ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
   // 方法体
}

主要分为以下两类:

  • 访问(控制)修饰符:
    修饰符当前类同一包内子孙类其他包
    public Y Y Y Y
    protected Y Y Y N
    default Y Y N N
    private Y N N N

    联合国(public)【其他包】、  国家(protected)【继承子孙】、  洲际(default)【同一包】、  个人(private)【当前类】

    • 共有的,以 public 修饰符指定,对任何地方的其他类都能访问。如果几个相互访问的 public 类分布在不同的包中,则需要导入相应 public 类所在的包。由于类的继承性,类所有的公有方法和变量都能被其子类继承。
    • public static void main(String[] arguments) {
         // ...
      }
      //Java 程序的 main() 方法必须设置成公有的,否则,Java 解释器将不能运行该类
    • 受保护的,以 protected 修饰符指定,能同一个包中的任何其他类访问,也能够被不同包中的子类访问.

      protected 访问修饰符 不能修饰 类 接口,方法和成员变量能够声明为 protected,但是接口的成员变量和成员方法不能声明为 protected。

      子类能访问 protected 修饰符声明的 方法 和 变量,这样就能保护不相关的类使用这些方法和变量

      /*下面的父类使用了 protected 访问修饰符,子类重载了父类的 openSpeaker() 方法*/
      class AudioPlayer {
         protected boolean openSpeaker(Speaker sp) {
            // 实现细节
         }
      }
       
      class StreamingAudioPlayer {
         boolean openSpeaker(Speaker sp) {
            // 实现细节
         }
      }
      /*如果把 openSpeaker() 方法声明为 private,那么除了 AudioPlayer 之外的类将不能访问该方法。
        如果把 openSpeaker() 声明为 public,那么所有的类都能够访问该方法。
        如果我们只想让该方法对其所在类的子类可见,则将该方法声明为 protected。*/
    • 默认的,也称为 default 修饰符在同一个包的类可以访问,不使用任何修饰符。

接口里的变量都隐式声明为 public static final, 而接口里的方法默认情况下访问权限为 default

/*如下例所示,变量和方法的声明可以不使用任何修饰符*/
String version = "1.5.1";
boolean processOrder() {
   return true;
}

 

    • 私有的,以 private 修饰符指定,在同一类内可见
      /*私有访问修饰符是最严格的访问级别,所以被声明为 private 的方法、变量和构造方法只能被所属类访问,并且 
      类 和 接口 不能声明为 private声明为私有访问类型的变量只能通过类中公共的 getter 方法 被外部类 访问 Private 访问修饰符的使用主要用来隐藏类的实现细节和保护类的数据。
      */ public class Logger { private String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; } } /* 该类中 format 变量为私有变量,所以其他类不能直接得到和设置该变量的值。为了使其他类能够操作该变量,定义了两个 public 方法:getFormat() (返回 format的值)和 setFormat(String)(设置 format 的值)*/

       

    • /*访问控制和继承:以下是方法继承的规则:*/
      父类中声明为
      public 的方法在子类中也必须为 public。 父类中声明为 protected 的方法在子类中要么声明为 protected,要么声明为 public,不能声明为 private。 父类中声明为 private 的方法,不能够被继承
  • 非访问(控制)修饰符
    • static 修饰符,用来创建 类方法 和 类变量
      • 静态变量(类变量):static 关键字用来声明独立于对象(即不用对象实例化就可以访问)的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 局部变量不能被声明为 static 变量。
      • 静态方法:static 关键字用来声明独立于对象的静态方法静态方法 不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。
      • 对类变量和方法的访问可以直接用 classname.variablename 和 classname.methodname 的方式访问。
        public class InstanceCounter {
           private static int numInstances = 0; //static 创建 类变量
           protected static int getCount() { //static 创建 类方法
              return numInstances;
           } 
           private static void addInstance() { //static 创建 类方法
              numInstances++;
           }
         
           InstanceCounter() { // 构造器
              InstanceCounter.addInstance();
           }
         
           public static void main(String[] arguments) {
              System.out.println("Starting with " + InstanceCounter.getCount() + " instances"); //使用类方法,由于是静态方法,因此无需实例化就可以访问
              for (int i = 0; i < 500; ++i){
                 new InstanceCounter(); //调用构造器方法
              }
              System.out.println("Created " + InstanceCounter.getCount() + " instances");  //使用 类方法
           }
        }
    • final 修饰符,用来修饰 类、方法 和 变量,final 修饰的 不能够被 继承,修饰的方法 不能被继承类 重新定义,修饰的变量为常量,是不可修改的
      • final 变量:能被显式地初始化并且只能初始化一次。被声明为 final 的对象的引用不能指向不同的对象。但是 final 对象里的数据可以被改变。也就是说 final 对象的引用不能改变,但是里面的值可以改变;
      • final变量:final 修饰符通常和 static 修饰符一起使用来创建类常量
        public class Test{
          final int value = 10;
          // 下面是声明 类常量 的实例
          public static final int BOXWIDTH = 6;
          static final String TITLE = "Manager";
         
          public void changeValue(){
             value = 12; //将输出一个错误
          }
        }
      • final 方法:类中的 final 方法可以被子类继承,但是不能被子类修改,声明 final 方法的主要目的是防止该方法的内容被修改
        public class Test{
            public final void changeName(){
               // 方法体
            }
        }
      • final 类: 不能被继承,没有类能够继承 final 类的任何特性。
        public final class Test {
           // 类体
        }
    • abstract 修饰符:用来创建 抽象类 和 抽象方法
      • 抽象类: 抽象类不能用来实例化对象,声明抽象类的唯一目的为了将来对该类进行扩充

        一个类不能同时被 abstract 和 final 修饰。如果一个类包含抽象方法,那么该类一定要声明为抽象类,否则将出现编译错误。

        抽象类可以包含 抽象方法 和 非抽象方法。

        abstract class Caravan{
           private double price;
           private String model;
           private String year;
           public abstract void goFast(); //抽象方法
           public abstract void changeColor();
        }
      • 抽象方法: 抽象方法是一种没有任何实现的方法,该方法的的具体实现由子类提供

        抽象方法不能被声明成 final 和 static。

        任何继承抽象类的子类必须实现父类的所有抽象方法,除非该子类也是抽象类

        如果一个类 包含若干个抽象方法,那么该类必须声明为 抽象类。抽象类可以不包含抽象方法。

        抽象方法的声明以分号结尾,例如:public abstract sample();

        public abstract class SuperClass{
            abstract void m(); //抽象方法
        }
         
        class SubClass extends SuperClass{
             //实现抽象方法
              void m(){
                  .........
              }
        }
    • synchronizedvolatile 修饰符,主要用于线程的编程
      • synchronized 关键字声明的方法同一时间只能被一个线程访问。synchronized 修饰符可以应用于四个访问修饰符。eg:public synchronized void showDetaails(){.......}; 
      • transient 修饰符:序列化的对象包含被 transient 修饰的实例变量时,java 虚拟机(JVM)跳过该特定的变量。eg:public transient int limit = 55; // 不会持久化
      • volatile 修饰的成员变量在每次被线程访问时,都强制从共享内存中重新读取该成员变量的值。而且,当成员变量发生变化时,会强制线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。一个 volatile 对象引用可能是 null。
        public class MyRunnable implements Runnable{
            private volatile boolean active;
            public void run(){
                active = true;
                while (active) { // 第一行
                    // 代码
                }
            }
            public void stop(){
                active = false; // 第二行
            }
        }
        /*通常情况下,在一个线程调用 run() 方法(在 Runnable 开启的线程),在另一个线程调用 stop() 方法。 如果 第一行 中缓冲区的 active 值被使用,那么在 第二行 的 active 值为 false 时循环不会停止。
        但是以上代码中我们使用了 volatile 修饰 active,所以该循环会停止。  */

运算符

  • 算术运算符(+, -, *, /, %, ++, --)
    public class Test {
     
      public static void main(String[] args) {
         int a = 10;
         int b = 20;
         int c = 25;
         int d = 25;
         System.out.println("a + b = " + (a + b) );
         System.out.println("a - b = " + (a - b) );
         System.out.println("a * b = " + (a * b) );
         System.out.println("b / a = " + (b / a) );
         System.out.println("b % a = " + (b % a) );
         System.out.println("c % a = " + (c % a) );
         System.out.println("a++   = " +  (a++) );
         System.out.println("a--   = " +  (a--) );
         // 查看  d++ 与 ++d 的不同
         System.out.println("d++   = " +  (d++) );
         System.out.println("++d   = " +  (++d) );
      }
    }
    算术运算符 Test.java
  • 关系运算符(==, !=, >, <, >=, <=)
    public class Test {
     
      public static void main(String[] args) {
         int a = 10;
         int b = 20;
         System.out.println("a == b = " + (a == b) );
         System.out.println("a != b = " + (a != b) );
         System.out.println("a > b = " + (a > b) );
         System.out.println("a < b = " + (a < b) );
         System.out.println("b >= a = " + (b >= a) );
         System.out.println("b <= a = " + (b <= a) );
      }
    }
    关系运算符 Test.java
  • 位运算符:应用于整数类型(int),长整型(long),短整型(short),字符型(char),和字节型(byte)等类型。
    &: 如果相对应位都是1,则结果为1,其余全为0
    |: 如果相对应位都是0,则结果为0,否则为1
    ^: 如果相对应位值相同,则结果为0,否则为1
    ~: 按位补运算符翻转操作数的每一位,即0变成1,1变成0
    <<: 按位左移运算符。左操作数按位左移右操作数指定的位数
    >>: 按位右移运算符。左操作数按位右移右操作数指定的位数
    >>>: 按位右移补零操作符。左操作数的值按右操作数指定的位数右移,移动得到的空位以零填充
    eg:
    A = 0011 1100
    B = 0000 1101
    -----------------
    A&b = 0000 1100
    A | B = 0011 1101
    A ^ B = 0011 0001
    ~A= 1100 0011
    位运算符 
    public class Test {
      public static void main(String args[]) {
         int a = 60; /* 60 = 0011 1100 */ 
         int b = 13; /* 13 = 0000 1101 */
         int c = 0;
         c = a & b;       /* 12 = 0000 1100 */
         System.out.println("a & b = " + c );
     
         c = a | b;       /* 61 = 0011 1101 */
         System.out.println("a | b = " + c );
     
         c = a ^ b;       /* 49 = 0011 0001 */
         System.out.println("a ^ b = " + c );
     
         c = ~a;          /*-61 = 1100 0011 */
         System.out.println("~a = " + c );
     
         c = a << 2;     /* 240 = 1111 0000 */
         System.out.println("a << 2 = " + c );
     
         c = a >> 2;     /* 15 = 1111 */
         System.out.println("a >> 2  = " + c );
      
         c = a >>> 2;     /* 15 = 0000 1111 */
         System.out.println("a >>> 2 = " + c );
      }
    } 
    Test.java
  • 逻辑运算符(&&与,||或,!非)
    &&    称为逻辑与运算符。当且仅当两个操作数都为真,条件才为真。    (A && B)为假。
    | |    称为逻辑或操作符。如果任何两个操作数任何一个为真,条件为真。    (A | | B)为真。
    !    称为逻辑非运算符。用来反转操作数的逻辑状态。如果条件为true,则逻辑非运算符将得到false。    !(A && B)为真。
    public class Test {
      public static void main(String[] args) {
         boolean a = true;
         boolean b = false;
         System.out.println("a && b = " + (a&&b));
         System.out.println("a || b = " + (a||b) );
         System.out.println("!(a && b) = " + !(a && b));
      }
    }
    逻辑运算符 Test.java
  • 赋值运算符(=, +=, ....., (%)=,  左移位赋值运算符<<=,    右移位赋值运算符>>=,    按位与赋值运算符&=,  按位与会赋值运算符^=,  按位或赋值运算符 |=)
    public class Test {
      public static void main(String[] args) {
         int a = 10;
         int b = 20;
         int c = 0;
         c = a + b;
         System.out.println("c = a + b = " + c );
         c += a ;
         System.out.println("c += a  = " + c );
         c -= a ;
         System.out.println("c -= a = " + c );
         c *= a ;
         System.out.println("c *= a = " + c );
         a = 10;
         c = 15;
         c /= a ;
         System.out.println("c /= a = " + c );
         a = 10;
         c = 15;
         c %= a ;
         System.out.println("c %= a  = " + c );
         c <<= 2 ;
         System.out.println("c <<= 2 = " + c );
         c >>= 2 ;
         System.out.println("c >>= 2 = " + c );
         c >>= 2 ;
         System.out.println("c >>= a = " + c );
         c &= a ;
         System.out.println("c &= 2  = " + c );
         c ^= a ;
         System.out.println("c ^= a   = " + c );
         c |= a ;
         System.out.println("c |= a   = " + c );
      }
    } 
    赋值运算符 Test.java
  • 其他运算符: 
    条件(三元)运算符:variable x = (expression) ? value if true : value if false 
    instanceof运算符:检查该对象是否是一个特定类型(类类型或接口类型),格式:( Object reference variable ) instanceof  (class/interface type)

 

public class Test {
   public static void main(String[] args){
      int a , b;
      a = 10;
      // 如果 a 等于 1 成立,则设置 b 为 20,否则为 30
      b = (a == 1) ? 20 : 30;
      System.out.println( "Value of b is : " +  b );
 
      // 如果 a 等于 10 成立,则设置 b 为 20,否则为 30
      b = (a == 10) ? 20 : 30;
      System.out.println( "Value of b is : " + b );
   }
}
条件运算符 Test.java

 

/*如果运算符左侧变量所指的对象,是操作符右侧类或接口(class/interface)的一个对象,那么结果为真。 */
String name = "James";
boolean result = name instanceof String; // 由于 name 是 String 类型,所以返回真
instanceof 运算符 失落1
/** 如果被比较的对象兼容于右侧类型,该运算符仍然返回true。
 ** 在判断一个实例引用的类型时,使用的是实际类型,而不是声明的类型。
 */
class Vehicle {}

public class Car extends Vehicle {
    public static void main(String args[]){
        Car c1 = new Car();

        Vehicle v2 = new Car();    // v2 是 Car 类型
        Vehicle v3 = new Vehicle();

        //Car 是 Vehicle类型, Vehicle 不是 Car 类型
        boolean result1 =  c1 instanceof Vehicle;    // true
        boolean result2 =  v2 instanceof Car;        // true
        boolean result3 =  v2 instanceof Vehicle;    // true
        boolean result4 =  v3 instanceof Car;          // false

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
   }
}
instanceof 运算符 实例Car.java

 

循环结构:

  • while 循环: while(布尔表达式){ ...... }

    public class Test {
       public static void main(String args[]) {
          int x = 10;
          while( x < 20 ) {
             System.out.print("value of x : " + x );
             x++;
             System.out.print("\n");
          }
       }
    }
    while 循环  Test.java
  • do…while 循环:  do{....}while(布尔表达式) : 至少会执行一次

    public class Test {
       public static void main(String args[]){
          int x = 10;
     
          do{
             System.out.print("value of x : " + x );
             x++;
             System.out.print("\n");
          }while( x < 20 );
       }
    }
    do…while 循环 Test.java
  • for 循环:  for(初始化; 布尔表达式; 更新){.....}.

    public class Test {
       public static void main(String args[]) {
     
          for(int x = 10; x < 20; x = x+1) {
             System.out.print("value of x : " + x );
             System.out.print("\n");
          }
       }
    }
    for 循环 Test.java
public class Test {
    public static void main(String args[]) {
        for(int i=1;i<=9;i++){
            for(int j=1;j<=i;j++){
                System.out.print(j+"*"+i+"="+i*j+" ");
            }
            System.out.println();
        }
    }
}
for 循环 九九乘法表Test.java
  • Java5 引入了一种主要用于数组的增强型 for 循环,语法:

    for(声明语句 : 表达式){ //代码句子 }  
    /*声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配。其作用域限定在循环语句块,其值与此时数组元素的值相等。
    表达式:表达式是要访问的数组名,或者是返回值为数组的方法。 */
    public class Test {
       public static void main(String args[]){
          int [] numbers = {10, 20, 30, 40, 50};
          for(int x : numbers ){
             System.out.print( x );
             System.out.print(",");
          }
          System.out.print("\n");
    String [] names
    ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
    /*
    10,20,30,40,50,
    James,Larry,Tom,Lacy, */
  • break 和 continue 语句:
    • break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块;
      public class Test {
         public static void main(String args[]) {
            int [] numbers = {10, 20, 30, 40, 50};
       
            for(int x : numbers ) {
               // x 等于 30 时跳出循环
               if( x == 30 ) {
                  break;
               }
               System.out.print( x );
               System.out.print("\n");
            }
         }
      }
      break 关键字  Test.java
    • continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。
      public class Test {
         public static void main(String args[]) {
            int [] numbers = {10, 20, 30, 40, 50};
       
            for(int x : numbers ) {
               if( x == 30 ) {
              continue;
               }
               System.out.print( x );
               System.out.print("\n");
            }
         }
      }
      continue 关键字 Test.java

       

分支结构:

  • if 语句: if(布尔表达式 1){...}else if(布尔表达式 2){....}else{....}

  • switch 语句:

    switch(expression){
        case value :
           //语句
           break; //可选
        case value :
           //语句
           break; //可选
        //你可以有任意数量的case语句
        default : //可选
           //语句
    }
    public class Test {
       public static void main(String args[]){
          //char grade = args[0].charAt(0);
          char grade = 'C';
     
          switch(grade){
             case 'A' :
                System.out.println("优秀"); 
                break;
             case 'B' :
             case 'C' :
                System.out.println("良好");
                break;
             case 'D' :
                System.out.println("及格");
             case 'F' :
                System.out.println("你需要再努力努力");
                break;
             default :
                System.out.println("未知等级");
          }
          System.out.println("你的等级是 " + grade);
       }
    }
    switch 实例

 

Pre-article: Java 学习(4):基本数据类型,变量类型

Next: Java 学习(6):java Number & Math & String & 数组...常用类型

 

posted on 2017-08-07 16:54  云雀sunshine  阅读(281)  评论(0)    收藏  举报