ITPub博客

首页 > 应用开发 > Java > java 静态 构造 单例设计模式 匿名内部类 异常处理 手动异常

java 静态 构造 单例设计模式 匿名内部类 异常处理 手动异常

原创 Java 作者:笑平风 时间:2015-01-01 16:42:04 0 删除 编辑

静态代码块:  给类初始化

点击(此处)折叠或打开

  1. static
  2. {
  3.     System.out.println("a");
  4. }



构造代码块:  给对象初始化

点击(此处)折叠或打开

  1. {
  2.     System.out.println("b");
  3. }


构造函数: 给对应对象初始化

点击(此处)折叠或打开

  1. class StaticCode
  2. {
  3.     StaticCode(int x)
  4.     {
  5.         System.out.println("c");
  6.     }
  7. }


单例设计模式一(饿汉式,一般用这种方法)

点击(此处)折叠或打开

  1. class Student
  2. {
  3.     private int age;

  4. /**
  5.     此三部就是实现单例设计模式的代码
  6. */
  7.     private static Student s = new Student();
  8.     private Student(){}
  9.     public static Student getStudent()
  10.     {
  11.         return s;
  12.     }



  13.     public void setAge(int age)
  14.     {
  15.         this.age = age;
  16.     }
  17.     public int getAge()
  18.     {
  19.         return age;
  20.     }
  21. }

单例设计模式二(懒汉式,最好不用)


点击(此处)折叠或打开

  1. class Single
  2. {
  3.     private static Single s = null;
  4.     private Single(){}
  5.     public static Single getInstance()
  6.     {
  7.         if(s==null)
  8.         {
  9.             synchronized(Single.class)
  10.             {                
  11.                 if(s==null)
  12.                     s = new Single();
  13.             }
  14.         }
  15.         return s;
  16.     }
  17. }

匿名内部类(匿名内部类中的方法 最好不要超过3个  ,一个或两个就可以了)

点击(此处)折叠或打开

  1. abstract class AbsDemo
  2. {
  3.     abstract void show();
  4.     
  5. }


  6. class Outer
  7. {
  8.     int x = 3;
  9.     public void function()
  10.     {
  11.         AbsDemo d = new AbsDemo()
  12.         {
  13.             int num = 9;
  14.             void show()
  15.             {
  16.                 System.out.println(\"num===\"+num);
  17.             }
  18.             void abc()
  19.             {
  20.                 System.out.println(\"haha\");
  21.             }
  22.         };
  23. //或不把对象赋给 d ,直接在最后用 }.abc();

  24.         d.show();
  25.     }
  26. }

  27. class InnerClassDemo4
  28. {
  29.     public static void main(String[] args)
  30.     {
  31.         new Outer().function();
  32.     }
  33. }

异常处理

点击(此处)折叠或打开

  1. java 提供了特有的语句进行处理。
  2. try
  3. {
  4.     需要被检测的代码;
  5. }
  6. catch(异常类 变量)
  7. {
  8.     处理异常的代码;(处理方式)
  9. }
  10. finally
  11. {
  12.     一定会执行的语句;
  13. }

throws ArithmeticException,ArrayIndexOutOfBoundsException   声明异常


手动异常

点击(此处)折叠或打开

  1. class FuShuException extends Exception 
  2. {

  3. }

  4. class Demo
    {
    int div(int a,int b) throws FuShuException
    {
    if(b<0)
    throw new FuShuException(); 


    return a/b;
    }
    }





来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29798713/viewspace-1386934/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: java中的关键字
请登录后发表评论 登录
全部评论

注册时间:2014-08-09

  • 博文量
    75
  • 访问量
    194550