Java匿名对象基础用法

创建对象基本格式
类名称 对象名 = new 类名称();

就是只有右边的对象,没有左边的名字和赋值运算符
new 类名称();
匿名对象只能使用唯一的一次,下次再用就必须创建一个新对象所以适合一个对象只需要使用唯一的一次的情况

public class Person
{
    String name;
    public void showName()
    {
        System.out.println("我叫: " + name);
    }

}

public static void main(String[] args)
    {
        //左边的one 是对象的名字
        Person one = new Person();
        one.name = "sikadi";
        one.showName();
        System.out.println("============");

        //匿名对象
        new Person().name = "yuki";
        new Person().showName();
    }

在这里插入图片描述


匿名对象的使用

public static void main(String[] args)
    {
        //普通使用方式
//        Scanner sc = new Scanner(System.in);
//        int num = sc.nextInt();

        //匿名对象的方法
//        int num = new Scanner(System.in).nextInt();
//        System.out.println(num);

        //使用一般写法传入参数
//        Scanner sc = new Scanner(System.in);
//        method(sc);

        Scanner sc = methodReturn();
        int num = sc.nextInt();
        System.out.println("输入的是 " + num);

    }
    public static void method(Scanner sc)
    {
        int num = sc.nextInt();
        System.out.println("输入的是 " + num);
    }
    public static Scanner methodReturn()
    {
//        Scanner sc = new Scanner(System.in);
//        return sc;
        return new Scanner(System.in); //使用匿名对象来返回
    }

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值