当前位置 博文首页 > 墨辰柒的博客:实例化对象时仅声明,或等于null时状况

    墨辰柒的博客:实例化对象时仅声明,或等于null时状况

    作者:[db:作者] 时间:2021-08-02 21:39

    实例化对象时编译错误以及运行时抛出空指针异常状况

    public class Test {
        public static void main(String[] args) {
           //实例化对象时,只写右边,直接编译错误:Variable 'a' might not have been initialized
            NewQuestion a;
            System.out.println(a.testMethon());
            //实例化对象时,=null情况,运行时抛出异常:抛出 NullPointerException 异常
            NewQuestion b=null;
            System.out.println(b.testMethon());
            //正确的实例化方式 打印true 0 null
            NewQuestion c=new NewQuestion();
            System.out.println(c.testMethon()+"\t");
            //成员变量不写会有默认值
        }
    }
    
    package newqueastion;
    
    public class NewQuestion {
        int a;
        int[] b=null;
        public boolean testMethon(){
            return true;
        }
    }
    
    cs
    下一篇:没有了