java 实例化对象的2种方法

  • java中类,是引用型数据类型;

方法一:

class Person {
    String name;
    int age;
    public void tell(){
        System.out.println("姓名:" + name + ",年龄:" + age);
    }
}

public class ImoocStudent {

    public static void main(String[] args) throws Exception{
        Person per = new Person();
        per.name = "张三";// 如果不赋值,则为该类型默认值 null
        per.age = 23;
        per.tell();
    }

}

方法二:

class Person {
    String name;
    int age;
    public void tell(){
        System.out.println("姓名:" + name + ",年龄:" + age);
    }
}

public class ImoocStudent {

    public static void main(String[] args) throws Exception{
        //Person per = new Person();// 实例化方法一

        Person per = null;      // 实例化方法二
        per = new Person();// 见到new,开辟堆内存空间

        per.name = "张三";// 如果不赋值,则为该类型默认值 null
        per.age = 23;
        per.tell();
    }

}
posted @ 2023-06-01 16:31  盘思动  阅读(59)  评论(0编辑  收藏  举报