Create objects of a standard format:
Name = new class name of the object class name ();
Anonymous object is the only object on the right, with no name on the left and the assignment operator.
Note: Objects can only use anonymous unique times, and then not the next no longer create a new object.
Suggested Use: if it is determined there is a need to use the object only once, you can use an anonymous object.
Anonymous object as a parameter:
import java.util.Scanner;
//匿名类作为参数
public class Demo01Anonymose {
public static void main(String[] args) {
methodParam(new Scanner(System.in));
}
public static void methodParam(Scanner sc)
{
System.out.println("请输入一个数:");
int a = sc.nextInt();
System.out.println("你输入的数为:" + a);
}
}
Anonymous object as a return value:
import java.util.Scanner;
public class Demo02Anonymose {
public static void main(String[] args) {
Scanner sc = methodReturn();
System.out.println("请输入一个数:");
int a = sc.nextInt();
System.out.println("你输入的数为:" + a);
}
public static Scanner methodReturn()
{
return new Scanner(System.in);
}
}