-3

I want to create an anonymous class using a method that returns an instance of a class

class FirstClass {
    public FirstClass() {
        System.out.println("First class created");
    }
}

class SecondClass {
    public SecondClass() {
        System.out.println("Second class created");
    }
    public FirstClass getFirstClass() {
        return new FirstClass();
    }
}

public class Ex1 {
    public FirstClass getFirstClass() {
        return new FirstClass();
    }
    public static void main(String[] args) {
        //here is the problem
        Object obj = new SecondClass().getFirstClass() {
            {
                System.out.println("Anonymous class created");
            }
        };
    }
}

I expect program to work by creating the anonymous class, but it gives me a syntax error. Any solutions or workarounds are accepted. Thanks

  • 1
    https://stackoverflow.com/questions/355167/how-are-anonymous-inner-classes-used-in-java You're misunderstanding what anon classes are – Matthew Kerian Jun 24 '19 at 21:25
  • i have a task and thos are the conditions – Alex Jidras Jun 24 '19 at 21:26
  • 1
    You can't subclass an _instance_ of a class. That is a misunderstanding of what a subclass is. – khelwood Jun 24 '19 at 21:26
  • You clearly didn't read both your teacher's instructions nor the link I provided. – Matthew Kerian Jun 24 '19 at 21:27
  • i need to use anonymous class and create it from a reference to a class - thats the task – Alex Jidras Jun 24 '19 at 21:28
  • @AlexJidras Regardless, this is a very bad design pattern to use – EDToaster Jun 24 '19 at 21:30
  • Are you sure you're not supposed to be creating a subclass of `SecondClass` and possibly overriding `getFirstClass`? – khelwood Jun 24 '19 at 21:30
  • “…and create it from a reference to a class” what is “a reference to a class” in this context? The method `getFirstClass()` returns a reference to an object, not to a class. Further, when you use `new` you always create a new object and there’s no relationship between than new object and the object returned by `getFirstClass()`. – Holger Sep 02 '19 at 12:18

1 Answers1

0

You cannot create an anonymous class based on return value of a method. Anonymous classes can only be created upon creation of the object, meaning, it can only be created using a constructor.

Your best bet would be to just create FirstClass directly, and override the initializer, like so:

new FirstClass() {
    {
        System.out.println("This is from inside anon!");
    }
};

Community
  • 1
  • 1
EDToaster
  • 3,160
  • 3
  • 16
  • 25