Java匿名对象的使用

匿名对象:没有名字的对象
.
使用情景:确定一个对象只需要使用唯一的一次

使用格式:

(1) new 类名();
(2) new 类名().实例变量;
(3) new 类名().实例方法;

1.使用匿名对象调用实例变量和实例方法

public class Student{
    String name;
    public void study(){
        System.out.println("学习");
        System.out.println("姓名:"+name);
    }
}
public class Test {
    public static void main(String[] args) {
    //创建有名字的对象
    Student s = new Student();
    s.name = "张三";
    s.study();

    //创建匿名对象
    new Student().name = "李四";//匿名对象调用属性
    new Student().study();//匿名对象调用方法
    }
}

注意事项:

1.匿名对象可以调用属性但是没有意义
2.如果需要赋值,就不要使用匿名对象

2.使用匿名对象向方法传递参数

public class Test2 {

    public static void main(String[] args) {
        //正常方式传递参数
        /*
        Student s = new Student();
        param(s);
         */
        
        //使用匿名对象传递参数
        mParam(new Student());
    }
    
    public static void mParam(Student s){
        System.out.println("已经使用匿名对象传递参数!");
    }
        
}

3.使用匿名对象作为方法的返回值

public class Test3 {

    public static void main(String[] args) {
        mReturn();
    }
    
    public static Student mReturn(){
        //正常方式作为返回值
        /*
        Student s = new Student();
        return s;
         */
        
        //使用匿名对象作为返回值
        System.out.println("已经使用匿名对象作为返回值!");
        return new Student();
    }
        
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值