Day08

Day08

内部类

Outer.java

package com.susu2568.oop.Demo05;

public class Outer {
    private int id=20;
    public void out(){
        System.out.println("这是一个外部类");
    }

    public class Inter{
        public void in(){
            System.out.println("这是一个内部类");
        }

        //获得外部类的私有属性
        public void getId(){
            System.out.println(id);
        }
    }

}

Application.java

package com.susu2568.oop.Demo05;

public class Application {
    public static void main(String[] args) {
        Outer outer = new Outer();
        //通过外部类来实例化内部类
        Outer.Inter inter = outer.new Inter();
        inter.getId();
    }
}
//输出:
//20

一个java类中可以有多个class类 但只能有一个public class类

匿名类

package com.susu2568.oop.Demo05;
//匿名类
public class Test {
    public static void main(String[] args) {
        new Apple().eat();
        new userService() {
            @Override
            public void hello() {
            }
        };
    }
}

class Apple{
    public void eat(){
        System.out.println("1");
    }
}

interface userService{
    void hello();
}

异常

Day08

捕获和抛出异常

package com.susu2568.exception.Demo01;

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
//若需要捕获多个异常   需从小到大
        try {//监控区域
            new Test().a();
        }catch (Throwable e){//捕获异常
            System.out.println("程序异常");
        }finally {//做善后工作
            System.out.println("finally");
        }
        //快捷键  ctrl+alt+T
        try {

            if (b==0) {//throw
                throw new ArithmeticException();//抛出异常
            } else {System.out.println(a/b);
            }
        } catch (ArithmeticException e) {
            e.printStackTrace();//打印错误的栈信息
        } finally {
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}

自定义异常

package com.susu2568.exception.demo02;

public class myException extends Exception{
    private int detail;

    public void  myException(int a){
        this.detail = a;
    }

    @Override
    public String toString() {
        return "myException{" +
                "detail=" + detail +
                '}';
    }
}

package com.susu2568.exception.demo02;

public class Test01 {
     public void  test(int a) throws Exception{
        if (a>10){
            throw new myException();
        }
        System.out.println("ok");
    }

    public  void main(String[] args) throws Exception {
        try {
            test(10);
        } catch (myException e) {
            System.out.println("myException=>"+e);
        }
    }
}

上一篇:C++笔试题day08


下一篇:day08-常用API