The twelfth day of Java basic learning (inner classes, exception handling)

The inner class

1. Inner class: A class is defined inside another class, then the class is called an inner class.

2. The class file name of the inner class: outer class $ inner class
Benefits : It is easy to distinguish which outer class the class file belongs to.

3. Category
of inner class ① Member inner class
◆ Access method of member inner class:
◇ Method 1: Provide a method in the outer class to create an object of the inner class for access.
◇ Method 2: Directly create objects of inner classes in other classes.
Format: outer class. inner class variable name = new outer class ().new inner class ();
◆ Note: If it is a static inner class, then the format created in other classes: outer class. inner class variable name = new outer class.inner class();

//外部类
class Outer{    
    //成员变量
    int x = 100; // Outer.class文件被加载到内存的时候存在内存中。静态的成员数据是不需要对象存在才能访问。
    //成员内部类
    static class Inner{             
        static int i = 10;
        public void print(){
            System.out.println("这个是成员内部类的print方法!"+i);
        }
    }   
    //在外部的方法中创建了内部类的对象,然后调用内部方法。
    public void instance(){
        Inner inner = new Inner();
        inner.print();
    }
}
//其他类
class Demo12.1{
    public static void main(String[] args){
        System.out.println(Outer.Inner.i);

        Outer outer = new Outer();
        outer.instance();

        Outer.Inner inner = new Outer().new Inner();
        inner.print();

        Outer.Inner inner = new Outer.Inner();
        inner.print();
    }
}

② Local inner class: If another class is defined inside a method of a class, then the other class is called a local inner class.
◆ Details to be paid attention to in the local inner class:
◇ If the local inner class accesses a local variable, then the local variable must be modified with final,

class  Outer{
    String name= "外部类的name";
    public void test(){
        //局部变量
        final int y = 100; 
        //局部内部类
        class Inner{    
            int x = 10;
            public void print(){
                System.out.println("这个是局部内部类的print方法.."+y);
            }   
        }       
        Inner inner = new Inner(); 
        inner.print();
    }
}
class Demo12.2{
    public static void main(String[] args){
        Outer outer = new Outer();
        outer.test();
    }
}

③ Anonymous inner class
Anonymous inner class: A class without a class name is called an anonymous inner class.
The benefit of anonymous inner classes: simplifies writing.
Prerequisites for the use of anonymous inner classes: There must be an inheritance or implementation relationship before they can be used.
Anonymous inner classes are generally used for actual parameters.

abstract class Animal{  
    public abstract Animal run();
    public abstract void sleep();
}
class Outer{
    public void print(){
        //需求:在方法内部定义一个类继承Animal类,然后调用run方法与sleep()      
        /*//局部内部类
        class Dog extends Animal{           
            public void run(){
                System.out.println("狗在跑..");
            }
            public void sleep(){
                System.out.println("狗趴在睁开眼睛睡..");
            }
        }       
        //创建对象
        Dog d = new Dog();
        d.run();    
        d.sleep();
        */  
        //匿名内部类 :匿名内部类只是没有类名,其他的一概成员都是具备的
        //匿名内部类与Animal是继承的关系,目前是创建Animal子类的对象

        /*
        new Animal(){       
            public void run(){
                System.out.println("狗在跑..");
            }
        }.run();            
        */

        Animal a = new Animal(){  //多态      
            //匿名内部的成员 
            public Animal run(){
                System.out.println("狗在跑..");
                return this;
            }           
            public void sleep(){
                System.out.println("狗趴在睁开眼睛睡..");
            }
            //特有的方法
            public void bite(){
                System.out.println("狗在咬人..");
            }   
        };  
        a.run();
        a.sleep();      
    }
}
class Demo12.3{
    public static void main(String[] args){     
        Outer outer = new Outer();
        outer.print();  
    }
}

4. Application scenarios of internal classes: When we describe the A thing, we find that there is another more complex thing B inside the A thing described, and this more complex thing B also needs to access the attributes and other data of the A thing, then At this time, we can use the inner class to describe the B thing.

5, the benefits of inner classes: inner classes can directly access all members of the outer class.

6. Details to be paid attention to in the inner class
① If the outer class and the inner class have member variables with the same name, the inner class will access the member variables of the inner class by default. But you can specify access to the members of the outer class through "outer class.this.member variable name".
② The private member inner class can only provide a method in the outer class to create the object of the inner class for access, and cannot create objects in other classes.
③ Once a static member appears in an inner class of members, the class must also be modified with static.

2. Exception handling

1. Exception system
Throwable[ Error (error), Exception (exception: runtime exception, compile-time exception)]
① Throwable exception or superclass of error class

◆ Error error: Errors are generally used for problems caused by jvm or hardware , so we generally do not handle errors through code.
◆ Exception: It needs to be handled by code.

2. Commonly used methods of Throwable
① toString(): Returns the full class name + pathological information of the current exception object.
② getMessage(): Returns the string information passed in to create a Throwable.
③ printStackTrace(): Print exception stack information.

class Demo12.4{
    public static void main(String[] args){
        //创建了一个Throwable对象。
        Throwable t = new Throwable("头晕,感冒..");
        String info = t.toString();
        String message = t.getMessage();
        System.out.println("toString: "+ info);  // java.lang.Throwable  包名+类名 = 完整类名
        System.out.println("message: "+ message);
        test();
    }
    public static void test(){
        Throwable t = new Throwable();
        t.printStackTrace();
    }
}

3. Distinguish between errors and exceptions
◆ If abnormal information appears in the program, and if the class name of the abnormal information ends with Error, then it must be an error.
◆ If it ends with Exception, it must be an exception.

4. Exception handling
① Method 1: Capture processing
◆ Format of capture processing:

try{
        可能发生异常的代码;
}catch(捕获的异常类型 变量名){
        处理异常的代码....
}

◆ Details to be paid attention to in capture processing
◇ If the code in the try block has an exception and has been processed, the code outside the try-catch block can be executed normally.
◇ If there is an abnormal code in the try block, the code after the abnormal code in the try block will not be executed.
◇ A try block can be followed by multiple catch blocks, that is, a try block can catch multiple types of exceptions.
◇ A try block can capture multiple types of exceptions, but the types of exceptions to be captured must be captured from small to large, otherwise a compilation error will be reported.
② Method 2: Throwing processing
◆ Details to be paid attention to in throwing processing
◇ If a method internally throws a compile-time exception object, it must declare throwing on the method.
◇ If a method declared to throw a compile-time exception is called, the caller must handle the exception.
◇ If an exception object is thrown inside a method, the code after the throw statement will not be executed again (a method encounters the throw keyword, and the method will stop executing immediately).
◇ In one case, only one type of exception object can be thrown.

class Demo12.5{
    public static void main(String[] args){
        try{
            int[] arr = null;
            div(4,0,arr); //调用了一个声明抛出异常类型的方法
        }catch(Exception e){
            System.out.println("出现异常了...");
            e.printStackTrace();
        }       
    }
    public static void div(int a, int b,int[] arr) throws Exception,NullPointerException {
        if(b==0){
            throw new Exception(); //抛出一个异常对象...
        }else if(arr==null){
            throw new  NullPointerException();
        }
        int c = a/b;
        System.out.println("c="+c);
    }
}

③ throw and throws two keywords
◆ throw keyword is used inside the method, throws is used for the method sound declaration.
◆ The throw keyword is used to throw an exception object inside the method, and the throws keyword is used to declare the throw exception type on the method declaration.
◆ There can only be one exception object after the throw keyword, and multiple types of exceptions can be thrown at a time after throws.

5. Customize the exception class
Steps : You can customize a class to inherit Exception.

/*
需求:模拟你去吃木桶饭,如果带钱少于了10块,那么就抛出一个没有带够钱的异常对象,如果带够了,那么就可以吃上香喷喷的地沟油木桶饭.
*/
//定义没钱的异常
class NoMoneyException extends Exception {
    public NoMoneyException(String message){
        super(message);
    }
}
class Demo12.6{
    public static void main(String[] args){
        try{
            eat(9);
        }catch(NoMoneyException e){
            e.printStackTrace();
            System.out.println("洗碗一个月!");
        }
    }
    public static void eat(int money) throws NoMoneyException{
        if(money<10){
            throw new NoMoneyException("吃霸王餐");
        }
        System.out.println("吃上了香喷喷的地沟油木桶饭!!");
    }
}

6. Finally block
① The premise of the use of finally block is that there must be a try block before it can be used.
② The code in the finally block will be executed under any circumstances, except when the jvm exits.
③ finally is very suitable for the work of resource release, so as to ensure that the resource file will be released under any circumstances.

/*
fianlly释放资源的代码
*/
import java.io.*;
class Demo12.7{
    public static void main(String[] args){
        FileReader fileReader = null;
        try{
            //找到目标文件
            File file = new File("f:\\a.txt");
            //建立程序与文件的数据通道
            fileReader = new FileReader(file);
            //读取文件
            char[] buf = new char[1024];
            int length = 0; 
            length = fileReader.read(buf);
            System.out.println("读取到的内容:"+ new String(buf,0,length));
        }catch(IOException e){
            System.out.println("读取资源文件失败....");
        }finally{
            try{
                //关闭资源
                fileReader.close();
                System.out.println("释放资源文件成功....");
            }catch(IOException e){
                System.out.println("释放资源文件失败....");
            }
        }
    }
}

7. Three combinations of try blocks
◆ The first: It is more suitable for those with exceptions to be handled but no resources to be released.

try{
    可能发生异常的代码
}catch(捕获的异常类型 变量名){
    处理异常的代码
}

◆ The second: It is more suitable for code that has both exceptions to be handled and resources to be released.

try{
    可能发生异常的代码
}catch(捕获的异常类型 变量名){
    处理异常的代码
}finally{ 
    释放资源的代码;
}

◆ The third type: It is more suitable for the runtime exception that is thrown internally, and there are resources to be released.

try{
    可能发生异常的代码
}finally{ 
    释放资源的代码;
}

Guess you like

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