创建对象基本格式
类名称 对象名 = 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); //使用匿名对象来返回
}