匿名类对象及可变个数形参的方法

匿名类对象:

当只需要调用一次类的对象时,可以考虑使用匿名的方式创建类的对象

特点,创建的匿名类的对象只能调用一次

new Circle().show();

new Circle.setRatius(2.4);

可变个数形参的方法:

/*
 可变个数的形参的方法
 1.格式: 对于方法的形参:数据类型 . . . 形参名
 2.可变个数的形参的方法与同名的方法之间构成重载
 3.可变个数的形参在调用时,个数从0开始,到无穷都可以
 4. 使用可变多个形参的方法与方法的形参使用数组是一样的
 5.若方法中存在可变个数的形参,那么一定要声明在方法形参的最后
 6.在一个方法中,最多只有一个可变个数的形参。
 */
public class TestArgs {
    public static void main(String[] args) {
        TestArgs t = new TestArgs();
        t.sayHello();
        t.sayHello(new String[] { "hello china", "say anhi" });
        t.sayHello("hello china", "say anhi");
    }

    // 如下三个方法构成重载
    public void sayHello() {
        System.out.println("hello ");
    }

    public void sayHello(String str1) {
        System.out.println("hello" + str1);
    }

    public void sayHello(String... args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }

    /*
     * public void sayHello1(String[] args) {//与上面的方法一致的 for (int i = 0; i <
     * args.length; i++) { System.out.println(args[i]); } }
     */

    public void sayHello(int i, String... args) {// 可变形参得写在后面
        System.out.println(i);
        for (int j = 0; j < args.length; j++) {
            System.out.println(args[j]);
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/afangfang/p/12481859.html
今日推荐