1.创建类
class Person{
String name;
int age;
String tel;
/*不带参构造函数*/
public Person() {
}
/*带参构造函数*/
public Person(String name, int age, String tel) {
super();
this.name = name;
this.age = age;
this.tel = tel;
}
/*成员方法*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
2.创建对象
类名 对象名=new 类名();
Person p1=new Person("Jack",23,"0123456789");
Person p2=new Person("Ada",21,"9876543210");
Person p3=new Person();
3.调用成员方法
p3.setAge(22);
p3.setName("July");
p3.setTel("99999999999");
4.对象引用
对象引用内存原理图
Person p4=new Person();
p4=p1;
p4.setName("Andy");
5.代码
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1=new Person("Jack",23,"0123456789");
Person p2=new Person("Ada",21,"9876543210");
Person p3=new Person();
p3.setAge(22);
p3.setName("July");
p3.setTel("99999999999");
System.out.print("p1\tAge:"+p1.getAge()+"\tname:"+p1.getName()+"\ttel:"+p1.getTel());
System.out.println();
System.out.print("p2\tAge:"+p2.getAge()+"\tname:"+p2.getName()+"\ttel:"+p2.getTel());
System.out.println();
System.out.print("p3\tAge:"+p3.getAge()+"\tname:"+p3.getName()+"\ttel:"+p3.getTel());
System.out.println();
Person p4=new Person();
p4=p1;
p4.setName("Andy");
System.out.print("p1\tAge:"+p1.getAge()+"\tname:"+p1.getName()+"\ttel:"+p1.getTel());
System.out.println();
}
}
6.结果
可以看到对象p3改变了对象p1中的name域