如何在Java匿名类中使用方法

问题描述 投票:-1回答:1

我如何在main方法内部的匿名类之外同时使用test()和aste()方法这两种方法?

java代码

    class Popcorn {
        public void taste() {
            System.out.println("Salty");
        }
    }

    public class Example1 {

        public static void main(String[] args) {

            Popcorn p2 = new Popcorn() {

        public void taste() {
                System.out.println("hi");
            }
                public void test() {
                    System.out.println("hi");
                }

            };

        // here I want to use test() and taste() both.

        }

    }
java anonymous-class anonymous-inner-class
1个回答
0
投票

您就像使用某个类实例的任何其他方法一样使用它。

您的实例称为p2,因此调用为:

p2.test();

类似,如果您想使用taste,只需:

p2.taste();
© www.soinside.com 2019 - 2024. All rights reserved.