静态代码块: 给类初始化
点击(此处)折叠或打开
- static
- {
- System.out.println("a");
- }
构造代码块: 给对象初始化
点击(此处)折叠或打开
- {
- System.out.println("b");
- }
构造函数: 给对应对象初始化
点击(此处)折叠或打开
- class StaticCode
- {
- StaticCode(int x)
- {
- System.out.println("c");
- }
- }
单例设计模式一(饿汉式,一般用这种方法)
点击(此处)折叠或打开
- class Student
- {
- private int age;
-
- /**
- 此三部就是实现单例设计模式的代码
- */
- private static Student s = new Student();
- private Student(){}
- public static Student getStudent()
- {
- return s;
- }
-
-
-
- public void setAge(int age)
- {
- this.age = age;
- }
- public int getAge()
- {
- return age;
- }
- }
单例设计模式二(懒汉式,最好不用)
点击(此处)折叠或打开
- class Single
- {
- private static Single s = null;
- private Single(){}
- public static Single getInstance()
- {
- if(s==null)
- {
- synchronized(Single.class)
- {
- if(s==null)
- s = new Single();
- }
- }
- return s;
- }
- }
匿名内部类(匿名内部类中的方法 最好不要超过3个 ,一个或两个就可以了)
点击(此处)折叠或打开
- abstract class AbsDemo
- {
- abstract void show();
-
- }
-
-
- class Outer
- {
- int x = 3;
- public void function()
- {
- AbsDemo d = new AbsDemo()
- {
- int num = 9;
- void show()
- {
- System.out.println(\"num===\"+num);
- }
- void abc()
- {
- System.out.println(\"haha\");
- }
- };
- //或不把对象赋给 d ,直接在最后用 }.abc();
-
- d.show();
- }
- }
-
- class InnerClassDemo4
- {
- public static void main(String[] args)
- {
- new Outer().function();
- }
- }
异常处理
点击(此处)折叠或打开
- java 提供了特有的语句进行处理。
- try
- {
- 需要被检测的代码;
- }
- catch(异常类 变量)
- {
- 处理异常的代码;(处理方式)
- }
- finally
- {
- 一定会执行的语句;
- }
throws ArithmeticException,ArrayIndexOutOfBoundsException 声明异常
手动异常
点击(此处)折叠或打开
- class FuShuException extends Exception
- {
-
- }
-
- class Demo
{
int div(int a,int b) throws FuShuException
{
if(b<0)
throw new FuShuException();
return a/b;
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29798713/viewspace-1386934/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29798713/viewspace-1386934/