匿名对象:就是定义对象的简化形式
- 当对象只对方法进行一次性调用时用匿名对象
Student graduate = new Student();
new Student().show();//有效
//这种对成员数据的使用无效,语法正确
new Student().id = 123;
new Student().name = “zxc”;
//因为在内存中,匿名对象随语句结束而被释放,相当于每个都是新创建的对象
2.匿名对象可以作为实参进行传递
void printId(Student s){…}
main(){
printId(new Student(12003));
}
构造函数:
1.特点:与类名一致,且不带任何返回值类型(void也不能有)
如果没有显示构造构造函数,虚拟机会自动加上隐式无参构造函数
2.构造函数本质是用于初始化对象属性,也可以限制用户创建对象格式
当某些对象一旦创建就带有固定属性就要有构造函数
构造函数有return 语句
关键字this:
1.为了提高程序的阅读性,在构造函数或者setXxx函数中的形参保持与类中的成员变量一致
并用用this来区分成员变量和局部变量
this本质是当前对象的地址的引用(哪个对象调用了this所在的函数,this就指向哪个对象)
2.为了 提高代码复用性,在多个构造函数中,构造函数调用构造函数要用this关键字
且必须写在构造函数第一行,因为初始化动作要先执行
class Student
{
int id; //默认为0
String name ;//默认为null
Student()
{}//空构造函数
Student(int id)
{
this.id = id;//用this来指明对象成员,即将局部变量的id赋值给成员变量的id
}
Student(int id,String name)
{
this(id);//调用已存在的构造函数来初始化参数
//此语句必须写在当下函数的第一行
this.name = name;
public static void show()
{
System.out.println("id="+id+"name:"+name);
}
//this 应用:凡是用到本对象中的成员都要用this
//判断是否是同一个学号
public boolean compare(Student s)
{
if(this.id == s.id)
return true;
else return false;
}
class ObjectDemo
{
public static void main(String[] args)
{
Student s = new Student();
Student s1 = new Student(12001);
Student s2 = new Student(12002,"Joy");
s1.compare(s2);
}
}