定义一个类
class Person {
String name;
//人的姓名
int age;
//人的年龄
public void talk(){
//定义说话的方法
System.out.print("姓名是:"+name+"年龄是:"+age);
}
}
定义类并在主方法中调用属性和方法 类声明对象调用类中属性和方法
class Persons3 {
String name;
//人的姓名
int age;
//人的年龄
public void talk(){
//定义说话的方法
System.out.print("姓名是:"+name+",年龄是:"+age);
}
}
public class OO1Demo3{
public static void main(String args[]){
Persons3 per=new Persons3();
//产生实例化对象
per.name="阿三";
//为名字赋值
per.age=20;
//为年龄赋值
per.talk();
//调用方法
}
}
同一类声明两个对象,分别调用属性和方法
class Person5 {
String name;
//人的姓名
int age;
//人的年龄
public void talk(){
//定义说话的方法
System.out.println("姓名是:"+name+"年龄是:"+age);
}
}
public class OODemo5{
public static void main(String args[]){
Person5 per1=null;
Person5 per2=null;
per1=new Person5();
per2=new Person5();
per1.name="阿三";
//为名字赋值
per1.age=20;
//为年龄赋值
per1.talk();
//调用方法
per2.name="蛋蛋";
per2.age=20;
per2.talk();
}
}
引用传递
package com.mz;
class Person6 {
String name;
//人的姓名
int age;
//人的年龄
public void talk(){
//定义说话的方法
System.out.println("姓名是:"+name+"年龄是:"+age);
}
}
public class OODemo6{
public static void main(String args[]){
Person6 per1=null;
Person6 per2=null;
per1=new Person6();
per2=per1;
//引用传递
per1.name="阿三";
//为名字赋值
per1.age=20;
//为年龄赋值
per1.talk();
//调用方法
per2.name="蛋蛋";
per2.age=20;
per2.talk();
per1.talk();
//这时堆内存储的信息早更改了,而且这是产生了内存垃圾
}
}