【格式 5-2 对象的创建】
类名 对象名称 = null;//声明对象
对象名称 = new 类名();//实例化对象
HelloWorld hello = null;
hello = new HelloWorld;
//合并
类名 对象名称 = new 类名();
HelloWorld hello = new HelloWorld();
【格式 5-3 访问对象中的属性或方法】
访问属性:对象名称.属性名
访问方法:对象名称.方法名
per.name="张乐";
per.tell();
【例 5.2】为对象的属性设置内容,同时调用 tell() 方法把内容输出
package oop_chapter5;
public class Person {
String name;//声明姓名属性
int age;//声明年龄属性
public void tell(){//取得信息的方法
System.out.println("姓名:"+name+",年龄:"+age);
}
}
public class ClassDemo03{
public static void main(String[] args) {
Person per = new Person();//创建并实例化对象
per.name="张乐";//为name属性赋值
per.age=25;//为age属性赋值
per.tell();//调用类中的方法
}
}
程序运行结果:
Attention:对象使用前必须实例化!-->Exception ini thread "main"java.lang.NullPointerException