0

how can I use both methods that test() and taste() method outside the anonymous class that is inside the main method?

java code

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.

    }

}
marstran
  • 26,413
  • 5
  • 61
  • 67
Kundan Kumar
  • 159
  • 2
  • 8
  • 1
    Did you even try to call the method before asking here? Did you get any error that made you ask the question in the first place? – lealceldeiro Feb 22 '20 at 11:01
  • 1
    You can use `taste()` by just `p2.taste()`. You can not use `test()` from outside, since all you know about `p2` is that it is a `Popcorn`. And `Popcorn`s usually have no `test` method (look at your class definition). – Zabuzard Feb 22 '20 at 11:05
  • Note that `var` (Java 10) actually allows this. Although this is one of the var-tricks that probably should not be used in production. – Zabuzard Feb 22 '20 at 11:29

0 Answers0