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();
}
}
相信坚持的力量,日复一日的习惯.

浙公网安备 33010602011771号